Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to compare date in Entity Framework

I am using date in where clause in Entity Framework and getting following error:

enter image description here

It is due to the below code:

var entity = dbContext.MyTable
                      .Where(w => w.PId = 3 && w.CreatedOn.Date == mydate.Date)
                      .First();

If I convert data into list using .ToList(), then compare to date, it will work fine but if I do so then it will pull data first into code then filter it out. Please help me out with this issue. Currently I am using a stored procedure to resolve the issue but really want this to work.

like image 922
Manprit Singh Avatar asked Dec 02 '15 18:12

Manprit Singh


1 Answers

You can use DbFunctions.TruncateTime canonical function like this

var entity = dbContext.MyTable
    .Where(w => w.PId == 3 && DbFunctions.TruncateTime(w.CreatedOn) == mydate.Date)
    .First();
like image 118
Ivan Stoev Avatar answered Sep 24 '22 09:09

Ivan Stoev