Entity Framework - Eager loading related entities

后端 未结 4 1355
野趣味
野趣味 2021-02-13 19:17

I\'m using Entity Framework 4 with MVC and need to ensure any referenced entities I want to use in my view have been loaded before the controller method returns, otherwise the v

相关标签:
4条回答
  • 2021-02-13 19:49

    I think this is a job for your repository which should in your case expose methods like GetFullSeller (all properties loaded by Include) and GetSeller (only base entity).

    Edit:

    There are several ways how to load navigation properties in EF v4.

    • Eager loading (using Include)
    • Lazy loading
    • Explicit loading by ObjectContext.LoadProperty (doesn't work for POCO)

    There is no automatic loading.

    0 讨论(0)
  • 2021-02-13 19:54

    Rather than passing your actual domain objects (EntityObjects) to the view, you may want to use your controller to map them into a Model object that better represents what your view should actually be displaying. This will reduce the amount of logic required in your View, and have the pleasant side-effect of avoiding passing EntityObjects around after their context has expired.

    Edit based on your edit:

    No, the API doesn't have a way to take a single Entity Object and make every other Entity Object of its type which was loaded at the same time it was be lazy-populated with a particular property in one fell swoop. You are better off pulling all of the items out in the first place using the Include mention like you show in your question.

    0 讨论(0)
  • 2021-02-13 20:09

    This is an old question, but in EF6 you can accomplish loading dependent objects on an entity like this:

    context.Entry(seller).Collection(s => s.Recommendations).Query().Include(r => r.User)).Load();
    

    That would load all Recommendations and their related Users for the given seller

    0 讨论(0)
  • 2021-02-13 20:14

    I'm in the same situation. I think that with EF is very easy to fall in a 101 query problem.

    A solution can be to create a partial class of your Seller class (generated by EF) and implement a GetSubclassNameQ that return a IQueryable, and a GetSubclassNameQFull that return a IQueryable with eager loading.

    public partial class Seller{
    
      public IQueryable<Recommendation> GetRecommendationsQ(EntityContainer entitycontainer) {
        return entitycontainer.Recommendations;
      }      
    
      public IQueryable<Recommendation> GetRecommendationsQFull(EntityContainer entitycontainer) {
        return this.GetRecommendationsQ(entitycontainer).Include("Recommendations.User");
      }
    
      public IQueryable<Recommendation> GetRecommendationsQ() {
        return GetRecommendationsQ(new EntityContainer());
      }
    
      public IQueryable<Recommendation> GetRecommendationsQFull() {
        return this.GetRecommendationsQ().Include("Recommendations.User");
      }
    
    }
    
    0 讨论(0)
提交回复
热议问题