[英]Entity Framework - filtering and retrieving child entities on child entity condition
[英]“Where” clause in Entity Framework not retrieving child entities
這是交易。
我的模型中有兩個相關的表。 我們將name'em: reports
和subReports
。
提到這一點非常重要,因為我目前不知道reportId
的報告的reportId
,因此我需要使用一些參數來查找它。 好的,因此,如果我需要通過EntityFramework查詢reports
一個元素,請執行以下操作:
reports myReport = context.reports.Where(r=> r.startYear.Equals(2014) && r.endYear.Equals(2015) && r.reportCategoryId.Equals(1)).SingleOrDefault();
此行將檢索與信息匹配的唯一報告。
但這就是問題所在。 如果我要訪問myReport
應該具有的subReports
集合,那么事實證明該集合為空。 這是我的問題,我不知道為什么。 我的表正確相關。
如果我這樣更改查詢,那就很奇怪了:
reports myReport = context.reports.Where(r=> r.reportId.Equals(1)).SingleOrDefault();
已加載相關實體,並且集合具有其應具有的子報表。 看到不同? 我必須傳遞reportId
,但這不是我所需要的,因為正如我已經告訴您的那樣,我不知道reportId
。
你知道發生了什么嗎?
先感謝您 :)
您是否嘗試過這些技術中的任何一種?
using (var context = new BloggingContext())
{
// Load all blogs and related posts
var blogs1 = context.Blogs
.Include(b => b.Posts)
.ToList();
// Load one blogs and its related posts
var blog1 = context.Blogs
.Where(b => b.Name == "ADO.NET Blog")
.Include(b => b.Posts)
.FirstOrDefault();
// Load all blogs and related posts
// using a string to specify the relationship
var blogs2 = context.Blogs
.Include("Posts")
.ToList();
// Load one blog and its related posts
// using a string to specify the relationship
var blog2 = context.Blogs
.Where(b => b.Name == "ADO.NET Blog")
.Include("Posts")
.FirstOrDefault();
}
關於懶惰和渴望加載的一些評論
通常,我傾向於在沒有延遲加載的情況下工作。 我想知道何時加載我的實體,何時不加載(渴望加載)。
延遲加載可以關閉
完全通過在DbContext
上設置相應的屬性:
this.Configuration.LazyLoadingEnabled = false;
導航屬性未標記為虛擬時用於特定實體。 有關更多信息,請參見鏈接的MSDN文章。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.