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

EF or Linq: Get list that includes another list but filter the second list where its property is true

I have two Classes:

public Case() 
{ 
  public IList<CaseThirdParty> CaseThirdParties { get; private set; }
}

public CaseThirdParty() 
{
  public bool Received_Claim { get; private set; }
}

I am using ef core to get all Cases but only get
CaseThirdParties where Received_Claim is True, here is the query:

await _context.Cases.Include(c => c.CaseThirdParties)
              .Where(c => c.CaseThirdParties.Any(c => c.Received_Claim))
              .ToArrayAsync();

Or

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

await _context.Cases.Include(c => c.CaseThirdParties)
              .Where(c => c.CaseThirdParties.Where(c => c.Received_Claim).Count>0)
              .ToArrayAsync();

But it retrieves CaseThirdParties where Received_Claim is flase

>Solution :

If you use ef core 5.0 or later you can use Filtered include

https://docs.microsoft.com/en-us/ef/core/querying/related-data/eager#filtered-include

like this:

await _context.Cases.Include(case => case.CaseThirdParties.Where(c => c.Received_Claim))
              .ToArrayAsync();

if not you have to create an anonymous object with Case and CaseThirdParties like this:

await _context.Cases.Where(case => case.CaseThirdParties.Any(case3rd => case3rd.Received_Claim))
              .Select(case =>
              {
                Case = case,
                CaseThirdParties = case.CaseThirdParties.Where(c => c.Received_Claim))
              }
              .ToArrayAsync();
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