I am working in an MVC controller and getting this error. I know that I can't cast a string to date within a linq query, but I was wondering if someone can help me with a workaround for this. My model collects the date from the database as a string and I MUST keep it this way instead of setting it as DateTime in my model, but I did create a ViewModel that allows for conversion to DateTime first so that I can run the needed query.
My Model:
namespace advertise.Models
{
public class Advertise_Clicks
{
public int ID { get; set; }
public int bannerID { get; set; }
public int Clicks { get; set; }
public string ClickDate { get; set; }
}
}
My ViewModel:
namespace advertise.ViewModels
{
public class AdvertiseClicksTotals
{
public int bannerID { get; set; }
public int Clicks { get; set; }
public string ClickDateStr { get; set; }
public DateTime ClickDate
{
get
{
return (DateTime)MySqlCDateTimeUtil.MySQLDateStringToNullableDateTime(ClickDateStr);
}
}
}
}
My code generating error:
string[] arrCurrentMonthDateRange = MySqlCDateTimeUtil.GetMySQLDateRange(now);
DateTime statsStartDate = (DateTime)MySqlCDateTimeUtil.MySQLDateStringToNullableDateTime(arrCurrentMonthDateRange[0]);
DateTime statsEndDate = (DateTime)MySqlCDateTimeUtil.MySQLDateStringToNullableDateTime(arrCurrentMonthDateRange[1]);
var banners = from b in db.Banners
where b.ad_userID == userID
select new BannersData
{
ID = b.ID,
BannerName = b.BannerName,
LinkImage = b.LinkImage,
ImageBorder = b.ImageBorder,
Redirect = b.Redirect,
BActive = b.BActive,
Approved = b.Approved,
Alt = b.Alt,
Expires = b.Expires,
BannerTypeID = b.BannerTypeID,
ApprovedBool = b.Approved == 1,
ActiveBool = b.BActive == 1,
ImageBorderBool = b.ImageBorder == 1,
DisplayName = b.AdvertiseBanner.DisplayName,
TotalClicks = advertiseClicksTotals.ToList().Where(ac => ac.bannerID == b.ID && Convert.ToDateTime(ac.ClickDateStr) >= statsStartDate && Convert.ToDateTime(ac.ClickDateStr) <= statsEndDate).Sum(ac => ac.Clicks)
};
**The error is because of this part of the code
TotalClicks = advertiseClicksTotals.Where(ac => ac.bannerID == b.ID && ac.ClickDate >= statsStartDate && ac.ClickDate <= statsEndDate).Sum(ac => ac.Clicks)
Is there a way to get around this? (Please let me know if you need more code)