[英]When are records from related tables loaded with LINQ2SQL
假設我有兩個表:
並假設我有一個數據庫上下文:
var reports = db.Reports();
如何確保每個報告的所有評論都已加載?
此時,我想與數據庫斷開連接,但仍然可以訪問注釋。 (例如:)
reports[0].Comments[0].Subject
我假設報告和評論之間存在1-M FK關系(1個報告可以有很多評論)?
一種選擇是使用DataLoadOptions.LoadWith方法-類似於以下內容:
var reports = db.Reports();
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Reports>(r => r.Comments); // Ask for Comments along with reports
reports.LoadOptions = dlo;
現在,每次您選擇有關該數據上下文的報告時,注釋都將隨同它一起從數據庫中獲取。
請注意,注釋中的所有字段都將被選中-無法使用此方法選擇字段的子集。
另一個選項是具體要在Linq查詢中選擇的內容,例如
var myReportsList = from report in db.Reports
select new { // Using anonymous type, but could use a custom class
Report = report,
Comment = report.Comment.Detail, // for example
Subject = report.Comment.Subject
};
要了解何時運行查詢和關閉數據庫連接,您將需要了解:
喬恩·斯基克斯(Jon Skeets)的“ C#深入”對這些內容進行了很好的概述,而且我也聽說過有關“ Linq in Action”的很好的事情-另外,還有很多關於這些概念的博客文章,這些主題比我能做的要公正得多。在這里; o)
請記住,如果您使用LoadOptions定義多跳路徑(報表,注釋,另一個實體),則會通過效率很低的代碼加載第三跳和更多跳(如果與1:n關系相關):它們將執行每個家長一個查詢。 對於報告注釋,沒關系,將在2個查詢中獲取它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.