如何在 efcore 中查询在 dbset 的集合中满足条件的结果?

How can I query in efcore for results where a condition is met in a collection of a collection of the dbset?

实体(简体)如下:

class A 
{
  public Guid ID { get;set; }
  public string Name { get;set; }
  public ICollection<B> Bs { get;set; }
}

class B
{
  public Guid ID { get;set; }
  public ICollection<C> Cs { get;set; }
}

class C
{
  public Guid ID { get;set; }
  public string Key { get;set; }
}

我想查询所有 class A,其中 class C 的键 属性 等于 'test'。我试图做的是:

var as = await this._applicationDbContext.As
                        .Where(a=> a.Bs.Any(b => b.Cs.Any(c=> c.Key == 'test')))
                        .ToListAsync();

但我没有得到任何回报。我知道我可以先包含 Bs 然后再包含 Cs 并在代码中执行此操作,但应该有一种方法可以在 ef 查询中执行此操作?

您的查询应该有效,无论如何请尝试以下变体:

var as = await this._applicationDbContext.As
    .Where(a => a.Bs.SelectMany(b => b.Cs).Any(c => c.Key == 'test'))
    .ToListAsync();

您需要使用.Include()

.Where(a=> a.Bs.Any(b => b.Cs.Any(c=> c.Key == 'test'))).Include(a => a.
Bs).ThenInclude(b => b.Cs).ToListAsync();