4

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.

Nemesis
  • 135
  • 1
  • 1
  • 13

1 Answers1

5

Entity Framework Core 3.1

There is still no option in Entity Framework Core 3.1, 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.

Entity Framework Core 5.0 and above

Filtered include was introduced in EF Core 5.0.

var filteredBlogs = context.Blogs
        .Include(
            blog => blog.Posts
                .Where(post => post.BlogId == 1)
                .OrderByDescending(post => post.Title)
                .Take(5))
        .ToList();

More information here: https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager#filtered-include

Emin Mesic
  • 1,681
  • 2
  • 8
  • 18
  • Thanks, that's a real bummer. I wanted to avoid using queryfilter since that will give me way too many methods where I will have to add ignorequeryfilter which I believe gives the wrong picture about its requirement/necessity but I'd rather use that over mixing ef with raw sql. – Nemesis Nov 24 '19 at 10:34
  • 2
    You might want to update the answer as 5.0 really brought this feature: https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-5.0/whatsnew#filtered-include – Jan Mar 01 '21 at 16:30