9

I need to check if two dates are equal in Linq query and the dates come from two different tables (not as a parameter). I have looked at existing solutions on the web and also in SO. some are not applicable in my case and some are not elegant. just looking for better alternate solution if there is any.

sample query (need to compare only date portions):

var query = from t1 in Table1
            join t2 in Table2 on t1.Id equals t2.ForeignKeyId
            where t1.Id = someId
               && t1.Date1.Date.Equals(t2.Date2.Date)

this one fails with an error "'Date' is not supported in LINQ to Entitiies. Only initializers, entity members, and entity navigation properties are supported"

the post 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported has a solution which compares day,month and year separately. I tried to wrap it into an extension method, but it seems Linq doesn't like extension methods either. since the second date is not a variable, I can't use the other solution mentioned in the linked post (and I can't call "AddDays" method on a date inside Linq for some reason). It looks like there are many limitations with Date API in Linq.

Community
  • 1
  • 1
RKP
  • 5,285
  • 22
  • 70
  • 111

2 Answers2

16

Try to use DiffDays from EntityFunctions class. Personally never used this, but worth to try like this:

var query = from t1 in Table1
        join t2 in Table2 on t1.Id equals t2.ForeignKeyId
        where t1.Id = someId
           && EntityFunctions.DiffDays(t1.Date1, t2.Date2) == 0
Renatas M.
  • 11,694
  • 1
  • 43
  • 62
  • 1
    Thanks a lot. that works like a charm. I looked at the generated SQL and the date comparison is converted to DATEDIFF(day,t1.Date1,t2.Date2) = 0, which is correct. I didn't know about this "EntityFunctions" before. Thanks once again. – RKP Dec 28 '11 at 12:57
  • forgot to mention that I used slightly amended version of your code. I can't use "Date" property of "Datetime" as mentioned in my post, so I used "EntityFunctions.DiffDays(t1.Date1,t2.Date2) == 0" and it worked. – RKP Dec 28 '11 at 14:23
0

As far as I remember you can just compare dates using the == operator.

Glory Raj
  • 17,397
  • 27
  • 100
  • 203
Svarog
  • 2,188
  • 15
  • 21