15

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?

Jimbo
  • 22,379
  • 42
  • 117
  • 159
  • 1
    Can you not use `expiry_date` directly? `.Where(o => o.expiry_date >= DateTime.Now)`. – Oded Dec 06 '12 at 10:19
  • It must incorporate the date specified by the item but use the pre-determined time, so unfortunately not. Even making an expiry_date2 property wouldnt work because you'd have to do a ToList() first. – Jimbo Dec 06 '12 at 10:28
  • Go through link bellow.. [Check Dates Only in LINQ][1] [1]: http://stackoverflow.com/a/24380028/1833050 – Imran Athar Jun 24 '14 at 06:50

3 Answers3

31

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.

natenho
  • 5,231
  • 4
  • 27
  • 52
Euphoric
  • 12,645
  • 1
  • 30
  • 44
  • 8
    Just for the record, EntityFunctions is deprecated in EF6, replaced by [System.Data.Entity.DbFunctions](http://msdn.microsoft.com/en-us/library/system.data.entity.dbfunctions(v=vs.113).aspx). – natenho Jul 02 '14 at 14:57
6

You can use:

var result = await db.Articles
          .Where(TruncateTime(x.DateCreated) >= EntityFunctions.TruncateTime(DateTime.Now))
          .ToListAsync();
Tasos K.
  • 7,979
  • 7
  • 39
  • 63
Mostafa Marji
  • 245
  • 8
  • 19
2

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)
petro.sidlovskyy
  • 5,075
  • 1
  • 25
  • 29