Conditional Include in EF Core

So in my query I have multiple then include to include all the related data. In the last include statement I want to add a condition, but I am getting an “invalid lambda expression response because of my linq statements.

Class Sample1 
{
   public int Id { get; set; }
   public ICollection<Sample2> S2 { get; set;}
}
Class Sample2
{
   public Sample3 S3 { get; set; }
   public Sample1 S1 { get; set;}
}
Class Sample3
{
   public int Id { get; set; }
   public ICollection<Sample4> S4 { get; set;}
}
Class Sample4 
{
   public Sample3 S3 { get; set; }
   public Sample5 S5 { get; set;}
}
Class Sample5
{
   public int Id { get; set; }
   public bool isPresent { get; set;}
}

What I need is when I query Sample 1, I want it to include everything till Sample 3 but only to include Sample 4 if Sample5.IsPresent is true.This is the query I am sending

var sample = await dbcontext.Sample1.Include(s1 => s1.S2).ThenInclude(s2 => s2.S3)
    .ThenInclude(s3 => s3.S4.Where(s4 => s4.S5.isPresent)).FirstOrDefaultAsync(s => s.Id==id);

I have tried using Any instead of Where but that didn’t work either.
I’d really appreciate any help on this. I have tried doing what some answers on related questions had suggested but none seemed to work.

1 Answer

There is still no option in Entity Framework Core, here is opened issue:

https://github.com/aspnet/EntityFrameworkCore/issues/1833

This is added to the Backlog in milestone 5.0.0 few days ago.

You should try Query Include Filter or similar extensions. Otherwise you can mix lambda with query expression. See this topic: EF Query With Conditional Include.

Archive from: https://stackoverflow.com/questions/59014652/conditional-include-in-ef-core

Leave a Reply

Your email address will not be published. Required fields are marked *