Reputation: 5605
I would like to know how to load multiple level of entities; more specifically how to load multiple level of descendants of a single entity. Here is an example I created. Suppose that on a web interface, after creating a new product, I would like to display its category type. So we have a product of a certain category, and this category has a category type with a name:
[HttpPost]
public ActionResult DoSomething(Product product)
{
if (ModelState.IsValid)
{
productRepository.InsertOrUpdate(product);
productRepository.Save();
...
context.Entry(product).Reference(p => p.Category).Load();
string someString1 = product.Category.SomeProperty;
...
string someString2 = product.Category.CategoryType.Name;
...
Someone showed me how to load children after saving an object on another post (see someString1 in the example above), but I cannot figure out how to load grand-children (someString2).
There are examples on the net showing how to load a collection of entities and all related objects, but the omit to show how to load all the descendants of a single entity.
I am using ASP.Net MVC 3 with EF 4.1. And all this is quite new to me, so please bear with me.
Upvotes: 1
Views: 2150
Reputation: 30152
Ensure EagerLoading (not LazyLoading) is enabled.
If you are SHOWING data like this, you need to ensure this loading is all done inside of your ObjectContext. If you are saving data only, you could lazy load as long as you are using the data in the same ObjectContext.
Edit: Since you want to load all the related entities on the model you send in, try simply loading your entity as mentioned above, and then call TryUpdateModel(yourLoadedModel) to merge the values from ModelState with your loaded object and save it. Now you have all relationships as well as the values from the form.
Upvotes: 1
Reputation: 155
You can get it like this
context.Entry(product).Reference(p => p.Category).Load();
string someString1 = product.Category.SomeProperty;
...
context.Entry(product.Category).Reference(c => c.CategoryType).Load();
string someString2 = product.Category.CategoryType.Name;
Upvotes: 1
Reputation: 6050
See Eagerly Loading Multiple Levels of Entities and Explicitly loading related entities in http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx
Upvotes: 2
Reputation:
I'm working on EF4.1 project at the moment. I don't need to specify anything - child objects get loaded automatically. I just need to invoke a property on that object.
E.g.: customerObj.Address.County
Upvotes: 0