10

我只需要比较涉及datetime字段的 Linq 查询中的日期。但是,下面的语法会导致以下错误消息

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

有谁知道如何从datetime字段中提取日期?

var duplicate = from a in _db.AgentProductTraining
                where a.CourseCode == course.CourseCode &&
                a.DateTaken.Date == course.DateTaken.Date &&
                a.SymNumber == symNumber
                select a;
4

7 回答 7

15

这可能看起来有点迂回,但您可以使用 SqlFunctions 类的DateDiff方法来执行此操作。只需传入两个值并使用“Day”来查找它们之间的天数差异(如果它们在同一天,则应该为 0)。

如下所示:

from a in _db.AgentProductTraining
                where a.CourseCode == course.CourseCode &&
                SqlFunctions.DateDiff("DAY", a.DateTaken, course.DateTaken) == 0 &&
                a.SymNumber == symNumber
                select a;
于 2013-02-08T18:19:16.123 回答
12

可以EntityFunctions.TruncateTime()在命名空间下使用System.Data.Objects

前任。

db.Orders.Where(i => EntityFunctions.TruncateTime(i.OrderFinishDate) == EntityFunctions.TruncateTime(dtBillDate) && i.Status == "B")

像魅力一样工作。

更新

此函数仅在您通过 LINQ 查询实体时有效。不要在 LINQ-Object 中使用。

对于 EF6,使用 System.Data.Entity 命名空间下的 DbFunctions.TruncateTime()。

于 2013-12-05T09:52:03.577 回答
6

你可以这样做:

var data1 = context.t_quoted_value.Where(x => x.region_name == "Pakistan" 
                        && x.price_date.Value.Year == dt.Year
                        && x.price_date.Value.Month == dt.Month
                        && x.price_date.Value.Day == dt.Day).ToList();
于 2014-06-24T06:46:29.137 回答
3

你必须使用System.Data.Entity.DbFunctions.TruncateTime

于 2016-08-21T19:42:51.530 回答
2

试试这个

DateTime dt =course.DateTaken.Date;
var duplicate = from a in _db.AgentProductTraining
                where a.CourseCode == course.CourseCode &&
                a.DateTaken == dt &&
                a.SymNumber == symNumber
                select a;

如果 a.DateTaken 也包含时间,那么请参考这些链接来修改您的日期。
Date 属性不能在 LINQ To 实体中使用。

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

LINQ to Entities 不支持“日期”。仅支持初始化器、实体成员和实体导航属性

http://forums.asp.net/t/1793337.aspx/1

于 2013-07-01T05:42:17.810 回答
0

这就是我通过进行类似的日期搜索结束的方式,我还必须考虑时间(小时和分钟部分)

from x in _db.AgentProductTraining
                where 
                       x.CreatedOn.Year == mydacourse.DateTakente.Year
                    && x.CreatedOn.Month == course.DateTaken.Month
                    && x.CreatedOn.Day == course.DateTaken.Day
                    && x.CreatedOn.Hour == course.DateTaken.Hour
                    && x.CreatedOn.Minute == course.DateTaken.Minute
                select x;
于 2018-04-15T19:04:21.503 回答
-1

去掉 .Date 如果字段是 DateTime 它可以与 == 进行比较

var duplicate = from a in _db.AgentProductTraining
                where a.CourseCode == course.CourseCode &&
                a.DateTaken == course.DateTaken &&
                a.SymNumber == symNumber
                select a;
于 2015-04-11T18:51:59.997 回答