[英]Linq to Sql - Loading Child Entities Without Using DataLoadOptions?
是否可以在不使用DataLoadOptions的情況下在單個查詢中加載子實體?
我在asp.net Web應用程序中為每個請求使用一個數據上下文,並嘗試繞過linq to sql限制,一旦查詢執行后無法更改dataloadoptions。
謝謝。
如果您不介意指向數據上下文的鏈接(正如您所說的那樣),則可以編寫一個存儲過程,該存儲過程返回映射到對象的多個結果。 在這里閱讀更多相關信息 。
我找到了以下vb.net示例,它從IMultipleResults類型手動填充子實體:
Public Function GetSubjectsWithBooks() As List(Of Subject)
Dim results As IMultipleResults = Me.GetSubjectAndBooks
Dim Subjects = results.GetResult(Of Subject).ToList
Dim Books = results.GetResult(Of Book).ToList
For Each s In Subjects
Dim thisId As Guid = s.ID
s.FetchedBooks = (From b In Books Where b.SubjectId = thisId).ToList
Next
Return Subjects
End Function
這取自Jim Wooley(Link in Action作者之一)編寫的示例項目,該項目可在以下網址找到: http : //www.thinqlinq.com/Downloads/LinqToSqlBeyondTheBasics.zip
奧梅爾,這是你指的技術嗎?
Rob Conery的博客有一種方法可以使用他有的幫助類LazyList<T>
。 他還使用自定義對象來避免加入匿名類型問題。 我成功地使用它來從沒有DataLoadOptions的sql獲取父子關系。
我認為他在他的MVC店面視頻的Pt2或Pt3中都有它:
http://www.asp.net/learn/mvc-videos/video-351.aspx
http://www.asp.net/learn/mvc-videos/video-352.aspx
這假設你有一個名為Category(不是linq實體)的POCO和一個LazyList類:
var categories = (from c in _db.Categories
select new Category
{
CategoryID = c.CategoryID,
CategoryName = c.CategoryName,
ParentCategoryID = c.ParentCategoryID,
SubCategories = new LazyList<Category>(
from sc in _db.Categories
where sc.ParentCategoryID == c.CategoryID
select new Category
{
CategoryID = sc.CategoryID,
CategoryName = sc.CategoryName,
ParentCategoryID = sc.ParentCategoryID
})
});
當您第一次訪問子實體時,它們將被加載,因此您可以通過訪問它們來強制Linq到Sql加載它們:...-)但我不認為這就是您的想法。
你的情況如何? 您是否將子實體與父實體存儲在同一個表中,並希望使用一個查詢獲取它們?
加入怎么樣? 例如:
from a in Albums join o in Users on a.Owner equals o select new {a, o}
如果您的集合是EntitySet,那么您可以通過.Load()方法加載它:
Person p = ctx.Persons.First();
p.Addresses.Load();
使用包含...
var q = from u in context.Users.Include(“address”)...
會導致地址子對象也被填充。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.