简体   繁体   中英

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. 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? Is there a better way then the .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:

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. properties you want to load as an 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM