Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare Dates using LINQ to Entities (Entity Framework)

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?

like image 974
Jimbo Avatar asked Dec 06 '12 10:12

Jimbo


People also ask

What does Dbfunctions TruncateTime do?

TruncateTime(Nullable<DateTime>) When used as part of a LINQ to Entities query, this method invokes the canonical TruncateTime EDM function to return the given date with the time portion cleared.

What is the difference between EF and Linq?

Entity Framework is an object-relational mapping (ORM) framework for connecting C# code to external databases, usually SQL Server. LINQ is a query language embedded into C# and a set of extension methods in order to make it useful.


3 Answers

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.

like image 151
Euphoric Avatar answered Oct 24 '22 04:10

Euphoric


You can use:

var result = await db.Articles
          .Where(TruncateTime(x.DateCreated) >= EntityFunctions.TruncateTime(DateTime.Now))
          .ToListAsync();
like image 39
Mostafa Marji Avatar answered Oct 24 '22 02:10

Mostafa Marji


Please use:

return All().Where(o => EntityFunctions.CreateDateTime(o.expiry_date.Year, o.expiry_date.Month, o.expiry_date.Day, 17, 30, 0) >= DateTime.Now)
like image 23
petro.sidlovskyy Avatar answered Oct 24 '22 03:10

petro.sidlovskyy