Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF how to filter data by date

I' using EF 4, I have a property DateTimeStart in my entities with datein this format 16/08/2012 08:14:40, I would like query with EF and find all the entities within the date 16/08/2012 only. Using this code below code I receive this error

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

my code

 DateTime dateTimeNow = DateTime.UtcNow;
        DateTime dateNow = dateTimeNow.Date;
        return db.EventCustoms.Where(x => x.DataTimeStart.Date <= dateNow)
            .Select(y => new { y.EventId, y.EventTitle, y.DataTimeStart });
like image 569
GibboK Avatar asked Aug 16 '12 08:08

GibboK


2 Answers

DateTime dateTimeNow = DateTime.UtcNow;
DateTime dateTomorrow = dateTimeNow.Date.AddDays(1);
return db.EventCustoms.Where(x => x.DataTimeStart < dateTomorrow) 
            .Select(y => new { y.EventId, y.EventTitle, y.DataTimeStart }); 

[Edit] @GibboK, To elaborate a bit:

Entity Framework cannot translate the Date property on your DateTime object at the database side.

Your options are:

(1) (As above) To rethink your query and try for a solution that does not require a function call at the database side for each row in your table.... which is good for query performance too

(2) or if that isn't possible, you can make use of the EntityFunctions class, which exposes methods (such as TruncateTime) that can be translated by EF into the appropriate native function for the underlying data source.

e.g.

return db.EventCustoms
    .Where(x => EntityFunctions.TruncateTime(x.DataTimeStart) <= dateNow)
like image 68
Merenzo Avatar answered Nov 15 '22 12:11

Merenzo


DateTime dateTimeNow = DateTime.UtcNow;
        DateTime dateNow = dateTimeNow.Date;
        return db.EventCustoms.Where(
             x => EntityFunctions.DiffDays(x.DataTimeStart, dateNow) >= 0)
            .Select(y => new { y.EventId, y.EventTitle, y.DataTimeStart });
like image 29
Amiram Korach Avatar answered Nov 15 '22 11:11

Amiram Korach