Home > Net >  How can I query in efcore for results where a condition is met in a collection of a collection of th
How can I query in efcore for results where a condition is met in a collection of a collection of th

Time:06-01

The entities (simplified) are as follows:

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; }
}

I want to query for all of class A where the Key Property of class C equals 'test'. What I tried to do is:

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

But I am not getting anything back. I know I could include Bs and then Cs and do it in code, but there should be a way to do it in the ef query?

CodePudding user response:

Your query should work, anyway try the following variant:

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

CodePudding user response:

You need to use .Include()

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