Samy Sammour Samy Sammour - 9 months ago 64
ASP.NET (C#) Question

Error while converting nullable datetime to string in LINQ MVC

I am developing an MVC system with a Kendo UI. I have to send a "date" from a filter button in View to the controller and filter the LINQ. I used this code:

public ActionResult Grid_ReadLogAdminList([DataSourceRequest] DataSourceRequest request, string filterDate)
DateTime _temp;
if (!DateTime.TryParse(filterDate, out _temp))
_temp = DateTime.Now;

return Json(_context.Entities<LogAdmin>().NoTracking().OrderByDescending(l => l.TimeStamp)
.Where(f => f.TimeStamp.Value.ToString("dd.MM.yyyy") == _temp.ToString("dd.MM.yyyy"))
.Select(l => new LogAdminInfo
Id = l.Id,
Message = l.Message,
MessageTemplate = l.MessageTemplate,
Level = l.Level,
TimeStamp = l.TimeStamp,
Exception = l.Exception,
Properties = l.Properties,
LogEvent = l.LogEvent,

but it gave me an error with the ".Where". you should know that TimeStamp field is "datetime?" nullable datetime.

I received this Error:

LINQ to Entities does not recognize the method 'System.String
ToString()' method, and this method cannot be translated into a store

how can I fix the Error?


The error is pretty indicative LINQ to Entities does not support the ToString method, you should compare your dates using another approach.

Based on your code I assume you are only interested in the date part of the DateTime for comparison so I suggest you to try DbFunctions.TruncateTime Method:

Where(f => DbFunctions.TruncateTime(f.TimeStamp) == DbFunctions.TruncateTime(_temp))