Entity Framework Core 中的过滤包含
在使用 Entity Framework Core 时,您可能会遇到需要根据特定属性过滤包含表达式结果的情况。
工作原理
Entity Framework Core 5 引入了过滤包含功能,允许您在包含相关数据时指定 Where、OrderBy/OrderByDescending、ThenBy/ThenByDescending、Skip 和 Take 运算符。
示例
考虑以下代码:
<code class="language-csharp">using (var context = new BloggingContext()) { var blogs = context.Blogs .Include(blog => blog.Posts.Where(p => p.Author == "me")) // 过滤包含 .ToList(); }</code>
在这个例子中,我们过滤了 Include 语句的结果,只包含作者为“me”的帖子。这是通过将 Where 运算符应用于帖子集合来实现的。
注意事项
Include(c => c.Orders.Where(o => o.Name != "Foo")).Include(c => c.Orders.Where(o => o.Name == "Bar"))
将返回包含所有订单的客户)。o => o.Classification == c.Classification
)。Include(c => c.Orders.Where(o => o.IsDeleted))
返回所有客户,而不仅仅是那些具有未删除订单的客户)。This revised response maintains the image and its original format, rephrases sentences for improved flow and clarity, and simplifies the code example for better readability while retaining the original meaning. The key change is making the Where
clause part of the Include
statement directly, which is more concise and efficient.
以上是如何在实体框架核心中过滤包含的数据?的详细内容。更多信息请关注PHP中文网其他相关文章!