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?

3
  • 1
    Can you not use expiry_date directly? .Where(o => o.expiry_date >= DateTime.Now). Commented Dec 6, 2012 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. Commented Dec 6, 2012 at 10:28
  • Go through link bellow.. [Check Dates Only in LINQ][1] [1]: stackoverflow.com/a/24380028/1833050 Commented Jun 24, 2014 at 6:50

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Just for the record, EntityFunctions is deprecated in EF6, replaced by System.Data.Entity.DbFunctions.
6

You can use:

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

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.