简体   繁体   English

使用LINQ to Entities(实体框架)比较日期

[英]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 LINQ to Entities中仅支持无参数构造函数和初始值设定项

Does anyone know how I can fix this? 有谁知道我怎么解决这个问题?

Use EntityFunctions instead. 请改用EntityFunctions Maybe CreateDateTime method. 也许CreateDateTime方法。

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. 使用EF6时,请改用DbFunctions

You can use: 您可以使用:

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

请用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM