【问题标题】:LINQ to Entities does not recognize the method 'Boolean Exists(System.Predicate`1[Entities.Connection])' methodLINQ to Entities 无法识别“Boolean Exists(System.Predicate`1[Entities.Connection])”方法
【发布时间】:2017-03-13 10:52:35
【问题描述】:

我尝试创建满足两个条件之一的笔记列表。 1.与创建的用户匹配。 2. 或与连接链接。

使用下面的代码会返回异常。我知道这个例外对于 Linq 来说是很常见的。但我的问题是可以使用哪些替代方法来代替 Exists?

“LINQ to Entities 无法识别方法 'Boolean Exists(System.Predicate`1[Entities.Connection])' 方法,并且该方法无法转换为存储表达式。”

_context.Notes
        .Include(t => t.Connections)
        .Where(t => t.CreatedUserId == userId || t.Connections.ToList().Exists(c => c.UserId == userId))

【问题讨论】:

  • 您是否尝试搜索您的错误?有任意数量的duplicates 会给你答案。
  • 是的,这是 SO 中非常常见的错误消息。无论如何,错误信息很明确,linq to entity 不支持存在,您应该尝试使用 Any() 或 Contains()。

标签: c# entity-framework linq linq-to-entities


【解决方案1】:

这里的问题是实体框架不理解你的 C# 代码并且不能解析 .Exists()。

另一种写法如下:

_context.Notes
    .Include(t => t.Connections)
    .Where(t => t.CreatedUserId == userId || t.Connections.Any(c => c.UserId == userId));

如果任何连接的 UserId 等于 userId,.Any() 将返回 true。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多