Compare Dates using LINQ to Entities (Entity Framework)

c# datetime entity-framework

Question

I need to return a list of items from my database that expire at a pre-specified time on the date supplied by the item. My erroneous code is as follows:

return All().Where(o => new DateTime(o.expiry_date.Year, o.expiry_date.Month, o.expiry_date.Day, 17, 30, 0) >= DateTime.Now)

The error I get is:

Only parameterless constructors and initializers are supported in LINQ to Entities

Does anyone know how I can fix this?

1
14
12/6/2012 10:17:14 AM

Accepted Answer

Use EntityFunctions instead. Maybe CreateDateTime method.

So maybe like this:

return All().Where(o => EntityFunctions.CreateDateTime(o.expiry_date.Year, o.expiry_date.Month, o.expiry_date.Day, 17, 30, 0) >= DateTime.Now)

Update:

When using EF6, use DbFunctions instead.

30
7/2/2014 3:03:12 PM

Popular Answer

You can use:

var result = await db.Articles
          .Where(TruncateTime(x.DateCreated) >= EntityFunctions.TruncateTime(DateTime.Now))
          .ToListAsync();


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow