Reputation: 2465
I am developing an asp.net 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,
})
.ToDataSourceResult(request));
}
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 expression.
how can I fix the Error?
Upvotes: 1
Views: 787
Reputation: 45967
replace
.Where(f => f.TimeStamp.Value.ToString("dd.MM.yyyy") == _temp.ToString("dd.MM.yyyy"))
with
.Where(f => DbFunctions.TruncateTime(f.TimeStamp) == _temp)
Upvotes: 1
Reputation: 3835
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))
Upvotes: 1
Reputation: 157
var tempDate = _temp.ToString("dd.MM.yyyy")
Json(_context.Entities<LogAdmin>().NoTracking().OrderByDescending(l => l.TimeStamp)
.Select(l => new LogAdminInfo
{
Id = l.Id,
Message = l.Message,
MessageTemplate = l.MessageTemplate,
Level = l.Level,
TimeStamp = l.TimeStamp.Value.ToString("dd.MM.yyyy"),
Exception = l.Exception,
Properties = l.Properties,
LogEvent = l.LogEvent,
}).Where(l => l.TimeStamp = tempDate).Select(l)
.ToDataSourceResult(request));
Upvotes: 0