asp.net mvc中的LINQ + EntityFunctions

我有这样的代码使用EntityFramework Alpha3(来自nuget):

class Member { [Key] public int Key { get; set; } public string Forename { get; set; } public string Surname { get; set; } public string Sitename { get; set; } public DateTime? RegDate { get; set; } } class MembersContext : DbContext { public MembersContext() : base("Name=ConnectionString") { } public DbSet Members { get; set; } } public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { Database.SetInitializer(null); const int memberKey = 1001; using (var db = new MembersContext()) { var query = from m in db.Members where m.Key == memberKey && EntityFunctions.DiffDays(m.RegDate, DateTime.Now) > 0 select m; var member = query.FirstOrDefault(); } return View(); } } 

我试图在新的ASP.NET MVC项目中使用EntityFunctions(基于.net 4.5) – 它总是失败并出现错误:

 LINQ to Entities does not recognize the method 'System.Nullable`1[System.Int32] DiffDays(System.Nullable`1[System.DateTime], System.Nullable`1[System.DateTime])' method, and this method cannot be translated into a store expression. 

相同的代码在Console应用程序中完全正常。 有什么想法,有什么不对?

我怀疑在ASP.NET应用程序的情况下,您还有对System.Data.Entity的引用,并且您正在使用EntityFunctions类定义的System.Data.Entity

但是,Entity Framework 6已经删除了对System.Data.Entity的依赖,并在EntityFramework程序集中为此目的重新定义了所有必需的类。

这意味着,在您的控制台应用程序的情况下,我猜测是设计( System.Data.Entity未被引用)或偶然( System.Data.Entity被引用,但EntityFunctions类取自EntityFramework.dll ) ,正确版本的EntityFunctions (来自EntityFramework.dll )。

如果您使用的是任何版本的Entity Framework 6,请确保使用的EntityFunctions类可以在EntityFramework.dll找到,而不是System.Data.Entity 。 entity framework6中EntityFunctions.cs源代码

实际上,如果您使用Entity Framework 6,我建议删除对System.Data.Entity所有和任何引用 – 以避免将来出现任何混淆和错误。

您收到此错误的原因是,设计Linq to Entities将所有表达式转换为服务器查询。 所以它不知道如何将DiffDays转换为SQL。 尝试省略此方法并重写表达式。


更新:

EntityFunctions是Canonical函数,因此您可以在Linq to Entities中使用它们 。 所以唯一合理的解释是EF Alhpa版本。