Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading