[英]How do I get an entity and all of its related entities
我正在使用EF6,並且正在嘗試獲取實體列表。 對於列表中的每個實體,我希望它在一次調用中填寫子實體。
例如:
Order.Id
Order.ColletionOfItems
Item.Id
Item.OrderId
Item.ProductName
Item.CollectionOfOptions
Option.Name
Option.Value
using(var db = DbContext)
{ //I want to fill in everything during this call as I am using all of it in the
//The calling function.
OrderList = db.Orders.Select().include //This is where I am stuck
return OrderList;
}
我希望返回的集合具有所有訂單,與單個訂單關聯的所有項目以及與單個項目關聯的所有選項。
我該如何構建linq語句來做到這一點? 有沒有比.Include("MyMajicString")
更好的方法? 我的搜索導致幾乎沒有可接受的答復,我應該實際搜索什么?
您需要使用Include
擴展方法:
using(var db = new YourContext())
{
var OrderList = db.Orders.Include(o=>o.ColletionOfItems.Select(i=>i.CollectionOfOptions));
return OrderList;
}
您還可以使用DbQuery.Include
方法,該方法接收導航的路徑作為參數。 要作為string
加載的屬性:
using(var db = new YourContext())
{
var OrderList = db.Orders.Include("ColletionOfItems.CollectionOfOptions");
return OrderList;
}
但是最好使用第一個,因為它是強類型的。 使用第二種方法,您可能會在鍵入屬性之一的名稱時出錯,或者可以更改導航的名稱。 將來在模型中添加屬性,而忘記在路徑中重命名該屬性。
另一件事,請小心加載大量數據。 使用該查詢,您將加載所有訂單和相關屬性,因此,在將所需信息加載到應用程序之前,請嘗試先進行過濾(在Include
調用之后調用Where
方法)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.