EF Core中的条件包含

4

在我的查询中,我有多个ThenInclude语句来包含所有相关的数据。在最后一个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;}
}

我需要的是当我查询 示例1 时,我希望它包含从 示例3 开始的所有内容,但仅在 示例5.IsPresent 为 true 时才包括 示例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);

我尝试使用 Any 替换 Where,但也不起作用。 对此,我真的非常感激任何帮助。我已经尝试了一些相关问题答案中建议的方法,但似乎都不起作用。

1个回答

5

Entity Framework Core 3.1

目前在 Entity Framework Core 3.1 版本中还没有这个选项,这是一个已经被打开的问题:

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

几天前,这个问题被添加到了里程碑 5.0.0 中。

您可以尝试使用Query Include Filter 或类似的扩展。否则您可以混合使用 lambda 表达式和查询表达式。请参阅此主题:EF Query With Conditional Include

Entity Framework Core 5.0 及以上版本

Filtered include 是在 EF Core 5.0 中引入的。

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

更多信息请查看:https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager#filtered-include


谢谢,这真是个糟糕的事情。我想避免使用queryfilter,因为那会给我太多的方法,我必须添加ignorequeryfilter,我认为这会给出错误的需求/必要性的图片,但我宁愿使用它来代替混合ef和原始sql。 - Nemesis
2
你可能需要更新答案,因为5.0版本真正带来了这个功能:https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-5.0/whatsnew#filtered-include - Jan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接