"The specified type member 'Date' is not supported in LINQ "

"The specified type member 'Date' is not supported in LINQ "

_dbEntities.EmployeeAttendances.Where(x => x.DailyDate.Date.Equals(DateTime.Now.Date)).ToList();

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

如何在 linq 查询中根据当前日期获取员工数据?

如果 DailyDate 属性 已经只是一个日期,而不是日期和时间,那么最简单的方法就是使用:

// Outside the query so it becomes a constant, effectively
var today = DateTime.Today;
var employees = _dbEntities.EmployeeAttendances
                           .Where(x => x.DailyDate == today)
                           .ToList();

如果确实有时间(使上述失败),你总是可以使用:

// Outside the query so it becomes a constant, effectively
var today = DateTime.Today;
var tomorrow = today.AddDays(1);
var employees = _dbEntities.EmployeeAttendances
                           .Where(x => x.DailyDate >= today &&
                                       x.DailyDate < tomorrow)
                           .ToList();

... 或按照 Farhad 的回答建议使用 TruncateTime。不过,我仍然建议先评估 DateTime.Today

var today = DateTime.Today;
var employees = _dbEntities.EmployeeAttendances
                       .Where(x => EntityFunctions.TruncateTime(x.DailyDate) == today)
                       .ToList();

注意Today(如DateTime.Now)使用系统默认时区。你应该仔细考虑一下这是否是你想要的。

EntityFramework 无法将 DateTime.Date 转换为 SQL。因此,它无法生成预期的 SQL。如果您只想获得 Date 部分,则可以使用 EntityFunctions.TruncateTime()DbFunctions.TruncateTime()(基于 EF 版本)方法代替:

 _dbEntities.EmployeeAttendances
            .Where(x => EntityFunctions.TruncateTime(x.DailyDate) == DateTime.Now.Date)
            .ToList();

附加信息:

EntityFunctions 方法被称为 规范函数 。这些是一组功能,所有 Entity Framework 提供商都支持这些功能。这些规范函数将被转换为提供者的相应数据源功能。规范函数是访问核心语言之外的功能的首选方式,因为它们使查询保持可移植性。

您可以找到所有规范函数 here and all Date and Time Canonical Functions here

更新:

自 EF6 起,EntityFunctions 已弃用 System.Data.Entity.DbFunctions

不要在 EF 6 中使用 EntityFunctions。TruncateTime 在 DbFunctions 中 class:

DbFunctions.TruncateTime(x.DailyDate)

以防万一它可以帮助某人... 在 EF 6 中,EntityFunctions 已过时,请改用 DbFunctions class。 您可能希望包含命名空间 System.Data.Entity;

例如:

_dbEntities.EmployeeAttendances.Where(x => DbFunctions.TruncateTime(x.DailyDate) == DateTime.Now.Date).ToList();