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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13741399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:39:37  来源:igfitidea点击:

Compare Dates using LINQ to Entities (Entity Framework)

c#entity-frameworkdatetime

提问by Jimbo

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 erroneouscode 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?

有谁知道我该如何解决这个问题?

采纳答案by Euphoric

Use EntityFunctionsinstead. Maybe CreateDateTimemethod.

请改用EntityFunctions。也许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 DbFunctionsinstead.

使用EF6时,请改用DbFunctions

回答by petro.sidlovskyy

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)

回答by Mostafa Marji

You can use:

您可以使用:

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