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中文網其他相關文章!