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

前端 未结 4 1034
滥情空心
滥情空心 2021-01-16 11:21

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. Su

相关标签:
4条回答
  • 2021-01-16 11:59

    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 讨论(0)
  • 2021-01-16 12:04

    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.

    0 讨论(0)
  • 2021-01-16 12:06

    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

    0 讨论(0)
  • 2021-01-16 12:15

    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;
    
    0 讨论(0)
提交回复
热议问题