开发者

asp.net mvc 3 - How do you load children AND grand-children of an entity?

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 cat开发者_StackOverflow社区egory 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.


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


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;


Ensure EagerLoading (not LazyLoading) is enabled.

http://blogs.microsoft.co.il/blogs/gilf/archive/2010/06/22/eager-loading-with-repository-pattern-and-entity-framework.aspx

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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜