【问题标题】:Conditional Include in EF Core [duplicate]EF Core 中的条件包含 [重复]
【发布时间】:2020-03-19 17:32:13
【问题描述】:

所以在我的查询中,我有多个 then include 以包含所有相关数据。在最后一个包含语句中,我想添加一个条件,但由于我的 linq 语句,我得到了“invalid lambda expression 响应。

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;}
}

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

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,但这也没有用。 我真的很感激这方面的任何帮助。我已经尝试按照相关问题的一些答案的建议进行操作,但似乎没有任何效果。

【问题讨论】:

    标签: c# asp.net entity-framework asp.net-core entity-framework-core


    【解决方案1】:

    Entity Framework Core 3.1

    Entity Framework Core 3.1 中仍然没有选项,这里是打开的问题:

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

    这是几天前在里程碑 5.0.0 中添加到 Backlog 中的。

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

    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();
    

    更多信息在这里:https://docs.microsoft.com/en-us/ef/core/querying/related-data/eager#filtered-include

    【讨论】:

    • 谢谢,这真是太糟糕了。我想避免使用 queryfilter,因为这会给我太多的方法,我将不得不添加 ignorequeryfilter,我认为它给出了关于它的要求/必要性的错误图片,但我宁愿使用它而不是将 ef 与原始 sql 混合使用。跨度>
    • 您可能想要更新答案,因为 5.0 确实带来了这个功能:docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-5.0/…
    猜你喜欢
    • 2021-07-12
    • 2018-10-17
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多