LINQ to Entities Exception不支持指定的类型成员'Date'

neb*_*ula 99 linq-to-entities entity-framework

我在实现以下语句时遇到异常.

 DateTime result;
 if (!DateTime.TryParse(rule.data, out result))
     return jobdescriptions;
 if (result < new DateTime(1754, 1, 1)) // sql can't handle dates before 1-1-1753
     return jobdescriptions;
 return jobdescriptions.Where(j => j.JobDeadline.Date == Convert.ToDateTime(rule.data).Date );
Run Code Online (Sandbox Code Playgroud)

例外

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
Run Code Online (Sandbox Code Playgroud)

我知道异常意味着什么,但我不知道如何摆脱它.有帮助吗?

Sla*_*uma 221

您可以使用EntityFunctionsTruncateTime方法将属性正确转换为SQL:Date

using System.Data.Objects; // you need this namespace for EntityFunctions

// ...

DateTime ruleData = Convert.ToDateTime(rule.data).Date;
return jobdescriptions
    .Where(j => EntityFunctions.TruncateTime(j.JobDeadline) == ruleData);
Run Code Online (Sandbox Code Playgroud)


更新: EntityFunctions在EF6中弃用,使用DbFunctions.TruncateTime

  • 请注意,在EF6中不推荐使用`EntityFunctions`,现在应该使用`DbFunctions`. (26认同)
  • 为'EntityFunctions.TruncateTime`提示+1! (7认同)
  • > EF6中DbFunctions的命名空间是`System.Data.Entity`:https://msdn.microsoft.com/en-us/library/Dn220142(v = VS.113).aspx (2认同)

Jud*_*udo 100

LINQ to Entities无法将大多数.NET Date方法(包括您使用的转换)转换为SQL,因为没有等效的SQL.

解决方案是使用LINQ语句之外的Date方法,然后传入一个值.看起来好像Convert.ToDateTime(rule.data).Date导致错误.

在DateTime属性上调用Date也无法转换为SQL,因此解决方法是比较.Year .Month和.Day属性,这些属性可以转换为LINQ,因为它们只是整数.

var ruleDate = Convert.ToDateTime(rule.data).Date;
return jobdescriptions.Where(j => j.Deadline.Year == ruleDate.Year 
                       && j.Deadline.Month == ruleDate.Month 
                       && j.Deadline.Day == ruleDate.Day);
Run Code Online (Sandbox Code Playgroud)

  • 怎么样j =>`j.JobDeadline.Date`? (5认同)

Kin*_*tes 36

对于EF6,请改用DbFunctions.TruncateTime(mydate).


Mah*_*azi 8

ef6中的"EntityFunctions.TruncateTime"或"DbFunctions.TruncateTime"正在工作,但它在大数据中存在一些性能问题.

我认为最好的方法是这样做:

DateTime ruleDate = Convert.ToDateTime(rule.data);

DateTime  startDate = SearchDate.Date;

DateTime  endDate = SearchDate.Date.AddDay(1);

return jobdescriptions.Where(j.Deadline >= startDate 
                       && j.Deadline < endDate );
Run Code Online (Sandbox Code Playgroud)

它比使用日期的部分更好.因为查询在大数据中运行得更快.