【问题标题】:Unable to Apply Linq Where Clause to Linked Entity in Entity Framework Core无法将 Linq Where 子句应用于 Entity Framework Core 中的链接实体
【发布时间】:2019-07-31 11:53:04
【问题描述】:

我有一个EventEntity,其中有IEnumerable<Poc> PocEntity

public class EventEntity
{
    public Guid Id { get; set; }
    public IEnumerable<PocEntity> Poc { get; set; }
}

我正在尝试根据PocEntity 过滤EventEntity。所以我就这样尝试,

IQueryable<EventEntity> query = _context.Events.Where(x => x.Poc.Where(p => p.PocId.Equals(pocId)));

但我遇到了错误,我无法做到这一点。请协助如何做到这一点。我正在使用 EF Core。

我遇到两个错误, 错误一:

不能隐式转换类型 'System.Collections.Generic.IEnumerable' 到 'bool'

错误 2:

无法将 lambda 表达式转换为预期的委托类型,因为 块中的某些返回类型不可隐式转换 到委托返回类型

【问题讨论】:

  • 请提供错误信息
  • @rad 添加了错误消息

标签: c# linq entity-framework-core where-clause iqueryable


【解决方案1】:

错误是因为第一个 Where() 子句的参数类型错误。 x =&gt; x.Poc.Where(p =&gt; p.PocId.Equals(pocId)) 需要评估为布尔值。为此,您可以使用 Any() 而不是 Where():

IQueryable<EventEntity> query = _context.Events.Where(x => x.Poc.Any(p => p.PocId.Equals(pocId)));

【讨论】:

    【解决方案2】:

    问题在于第一个 where 条件:

    .Where(x => x.Poc.Where(p => p.PocId.Equals(pocId)));
    

    where 子句需要一个 bool 表达式,而它唯一得到的是一个集合:p.PocId.Equals(pocId)

    解决方案:只需在集合末尾添加Any(),如下所示:

    .Where(x => x.Poc.Where(p => p.PocId.Equals(pocId)).Any())
    

    【讨论】:

    • 那如何根据pocId进行过滤呢?请您协助如何重构查询?
    • 那么现在我会单独获得这个 Poc 的事件吗?或者此查询将返回具有此特定 Poc 的所有事件?我正在尝试根据 Poc Id 过滤事件,这样如果我通过 PocId 则需要列出与该 Poc 相关的所有事件
    • 此语句只获取Event 实体。如果您希望相关的Poc 也包含在结果中,则需要使用Include 方法:docs.microsoft.com/en-us/ef/ef6/querying/related-data
    猜你喜欢
    • 1970-01-01
    • 2018-10-12
    • 2021-01-20
    • 2023-03-29
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    相关资源
    最近更新 更多