LINQ to Entities DateTime Compare

I have a problem comparing dates in LINQ with entity expressions. I would like to check if DateTime == DateTime - whole day .

I wanted to do it like this:

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

The problem is that the above query is incorrect in LINQ due to the AddDays () method.

I tried using DbFunctions as shown 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 produce the expected results.

+5
source share
3 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 the problem may be that your date can have not only a date, but also a part of the time.

Therefore, so that you select only the date in your DateTime variable, you can do it as follows:

 date = date.Date; var datePlusOneDay = date.AddDays(1); 
+5
source

Another way that Linq-To-Entities should work, even if you cannot initialize the date before the request will 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); 
+3
source

You can achieve what you want using DbFunctions.TruncateTime , but only on either side of the equation:

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

All Articles