Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to Entities DateTime Compare

I have problem with comparing dates in LINQ to entities expression. I would like to check if DateTime == DateTime - whole day.

I wanted to do it like that:

 return context.Events.Any(x => 
                            x.UserId == id 
                            && x.Date >= date 
                            && x.Date < date.AddDays(1) 
                            && x.Type == EventType.StartWork);

The problem is that above query is not correct with LINQ because of AddDays() method.

I`ve tried to use DbFunctions like below:

return context.Events.Any(x => 
                            x.UserId == id 
                            && x.Date >= date 
                            && x.Date < DbFunctions.AddDays(date, 1) 
                            && x.Type == EventType.StartWork);

Also this one:

  return context.Events.Any(x => 
                                x.UserId == id 
                                && DbFunctions.TruncateTime(date.Date) == date.Date 
                                && x.Type == EventType.StartWork);

None of these queries are not giving expected results.

like image 315
miechooy Avatar asked Jul 20 '16 07:07

miechooy


People also ask

How do I compare two dates in LINQ query with time?

Meeting dates are stored in this table using the following format: May 2nd 2011 is (for example) formatted as 5/2/2011 . My requirement is to get the meetings between two dates (say, 4/25/2011 and 5/2/2011) and to write a query comparing a date with these two dates. Does it compare like 4/25/2011 < 4/26/2011?


2 Answers

Just create 2 dates:

var datePlusOneDay = date.AddDays(1);

return context.Events.Any(x => x.UserId == id 
                         && x.Date >= date 
                         && x.Date < datePlusOneDay 
                         && x.Type == EventType.StartWork);

Also I'm not sure but problem could be that your date can have not only date part but also time part.

So to be sure that you select only date part of your DateTime variable you can do like this:

date = date.Date;
var datePlusOneDay = date.AddDays(1);
like image 184
teo van kot Avatar answered Oct 15 '22 06:10

teo van kot


Another way that should work in Linq-To-Entities even if you can't initialize the date before the query is to use System.Data.Entity.DbFunctions.DiffDays:

return context.Events
    .Any(x => x.UserId == id && x.Date > date 
        && System.Data.Entity.DbFunctions.DiffDays(x.Date, date) < 1
        && x.Type == EventType.StartWork);
like image 21
Tim Schmelter Avatar answered Oct 15 '22 04:10

Tim Schmelter