有条件包含在 EF Core 中

Nem*_*sis 4 c# asp.net entity-framework entity-framework-core asp.net-core

因此,在我的查询中,我有多个 then include 以包含所有相关数据。在最后一个 include 语句中,我想添加一个条件,但由于我的 linq 语句,我收到了“无效的 lambda 表达式响应。

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;}
}
Run Code Online (Sandbox Code Playgroud)

我需要的是,当我查询Sample 1时,我希望它包含Sample 3之前的所有内容,但如果 Sample5.IsPresent 为 true,则仅包含Sample 4。这是我要发送的查询

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);
Run Code Online (Sandbox Code Playgroud)

我尝试使用Any而不是Where,但这也不起作用。我真的很感激任何帮助。我已经尝试按照相关问题的一些答案建议的方法进行操作,但似乎都不起作用。

Emi*_*sic 5

实体框架核心 3.1

Entity Framework Core 3.1 中仍然没有选项,这里是未解决的问题:

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

几天前,它被添加到里程碑 5.0.0 的待办事项列表中。

您应该尝试查询包含过滤器或类似的扩展。否则,您可以将 lambda 与查询表达式混合。请参阅此主题:带条件包含的 EF 查询

Entity Framework Core 5.0 及更高版本

EF Core 5.0 中引入了过滤包含。

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

更多信息请参见:https://learn.microsoft.com/en-us/ef/core/querying/lated-data/eager#filtered-include

  • 您可能想要更新答案,因为 5.0 确实带来了此功能:https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-5.0/whatsnew#filtered-include (2认同)