c# - LINQ to Entities 无法识别方法 'System.TimeSpan Subtract(System.DateTime)

标签 c# linq entity-framework

以下会引发错误:

public FieldViewer GetFieldViewByFieldIDIPAndUserByDate( int fieldID, string ip, string userID, DateTime date )
{
    return this.context.FieldViewers.Where( x =>
        x.Field.FieldID == fieldID &&
        x.Viewer.IPAddress == ip &&
        x.Viewer.User.Id == userID &&

        date.Subtract( x.Viewer.CreatedAt ).TotalMinutes >= 10 ).FirstOrDefault();
}

LINQ to Entities does not recognize the method 'System.TimeSpan Subtract(System.DateTime)' method, and this method cannot be translated into a store expression.

我该如何解决这个问题,因为我需要按查询减去。

最佳答案

解决此问题的一种方法是使用 LINQ to Objects 提供程序在 LINQ to Entities 提供程序之外执行过滤部分。为此,请在该操作之前附加对 AsEnumerable() 的调用:

public FieldViewer GetFieldViewByFieldIDIPAndUserByDate( int fieldID, string ip, string userID, DateTime date )
{
    return this.context.FieldViewers.Where( x =>
            x.Field.FieldID == fieldID &&
            x.Viewer.IPAddress == ip &&
            x.Viewer.User.Id == userID)
       .AsEnumerable()
       .Where(x => date.Subtract( x.Viewer.CreatedAt ).TotalMinutes >= 10)
       .FirstOrDefault();  
}

另一种方法是使用 specialized LINQ to Entities operations 之一, 比如 DiffMinutes .

关于c# - LINQ to Entities 无法识别方法 'System.TimeSpan Subtract(System.DateTime),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31563153/

相关文章:

c# - ASP.NET 站点和 SharePoint 站点有什么区别?

c# - 如何使用 LINQ 在 C# 中使用字典属性

c# - 使用 linq 列出循环操作

.net - EF4、事务范围和任务<>

c# - 将两个可能为空的列表与 linq 结合起来

c# - 使用相关/派生的 Ts 在泛型中进行转换

linq - 尝试使用表达式树过滤 Nullable 类型

entity-framework - 如何从 MetadataWorkspace 中仅提取存储过程?

.net - Linq - 对象内的列表不保存在 db.SaveChanges() 调用中

c# - 有条件地添加 CSS 类 - Asp.net