Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant solution to check if two dates are equal, in Linq (where the second date is NOT a parameter)

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.

like image 444
RKP Avatar asked Dec 28 '11 12:12

RKP


1 Answers

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
like image 146
Renatas M. Avatar answered Oct 24 '22 19:10

Renatas M.