gpt4 book ai didi

c# - 有条件地包含在 EF Core 中

转载 作者:行者123 更新时间:2023-12-03 23:50:18 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Filtering on Include in EF Core

(8 个回答)


8 个月前关闭。




所以在我的查询中,我有多个然后包含以包含所有相关数据。在最后一个包含语句中,我想添加一个条件,但由于我的 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 但只包括 示例 4 如果 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);

我试过使用 任意 而不是 哪里但这也不起作用。
我真的很感激这方面的任何帮助。我曾尝试按照相关问题的一些答案进行操作,但似乎没有任何效果。

最佳答案

Entity Framework 核心 3.1
Entity Framework Core 3.1 中仍然没有选项,这里是 open issue:
https://github.com/aspnet/EntityFrameworkCore/issues/1833

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


你应该试试 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

关于c# - 有条件地包含在 EF Core 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59014652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com