[英]How do I get an entity and all of its related entities
I am using EF6 and I am trying to get a list of entities. 我正在使用EF6,并且正在尝试获取实体列表。 For each entity in the list i want it to fill in the child entities in the one call.
对于列表中的每个实体,我希望它在一次调用中填写子实体。
For instance: 例如:
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;
}
I want the returned collection to have all the orders, all the items associated to the individual order and all the options associated to an individual item. 我希望返回的集合具有所有订单,与单个订单关联的所有项目以及与单个项目关联的所有选项。
How do I build my linq statement to do this? 我该如何构建linq语句来做到这一点? Is there a better way then the
.Include("MyMajicString")
? 有没有比
.Include("MyMajicString")
更好的方法? What should I actual search for because my searches have led to very few acceptable responses? 我的搜索导致几乎没有可接受的答复,我应该实际搜索什么?
You need to use the Include
extension method: 您需要使用
Include
扩展方法:
using(var db = new YourContext())
{
var OrderList = db.Orders.Include(o=>o.ColletionOfItems.Select(i=>i.CollectionOfOptions));
return OrderList;
}
You can also use the DbQuery.Include
method which receive as parameter the path of the nav. 您还可以使用
DbQuery.Include
方法,该方法接收导航的路径作为参数。 properties you want to load as an string
: 要作为
string
加载的属性:
using(var db = new YourContext())
{
var OrderList = db.Orders.Include("ColletionOfItems.CollectionOfOptions");
return OrderList;
}
But is better use the first one because is strongly typed. 但是最好使用第一个,因为它是强类型的。 With this second method you can make a mistake typing the name of one of the properties or you could change the name of the nav.
使用第二种方法,您可能会在键入属性之一的名称时出错,或者可以更改导航的名称。 properties in your model in the future and forget rename the property in the path.
将来在模型中添加属性,而忘记在路径中重命名该属性。
Another thing, be careful loading large amounts of data. 另一件事,请小心加载大量数据。 With that query, you are going to load all orders and the related properties, so, try to filter first (calling the
Where
method after the Include
call) before load the info you need to your application. 使用该查询,您将加载所有订单和相关属性,因此,在将所需信息加载到应用程序之前,请尝试先进行过滤(在
Include
调用之后调用Where
方法)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.