Base solution for your next web application
Open Closed

EF Core Eager Loading Related Entities #3602


User avatar
0
rickwheeler created

Since lazy loading is not yet added to EF Core, how do I eager load related entities for all get methods?

For example:

public class MyEntity : Entity
{
    public int MyRelatedEntityId { get; set; }
    public MyRelatedEntity Related { get; set; }
}

How do I make sure that all methods on IRepository<MyEntity> eager load and include MyRelatedEntity? This includes GetAll, GetById, Find etc


2 Answer(s)
  • User Avatar
    0
    rickwheeler created

    I think I figured it out.

    Make a custom Repository in the EfCore project like this

    public class MyEntityRepository :MyAppRepositoryBase<MyEntity>, IRepository<MyEntity>
    {
        public MyEntityRepository(IDbContextProvider<MyAppDbContext> dbContextProvider) : base(dbContextProvider) { }
    
        public override IQueryable<MyEntity> GetAll()
        {
            return base.GetAll().Include(x => x.MyRelatedEntity);
        }
    }
    

    Then in the PreInitialize method of EntityFrameworkCoreModule

    Configuration.ReplaceService<IRepository<MyEntity>, MyEntityRepository>();
    
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    You can also use EnsurePropertyLoadedAsync extension method of IRepository.