Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

c# - EntityFramework Eager Load all Navigation Properties

I'm using the Repository pattern with DI and IoC.

I have created a function in my Repository:

T EagerGetById<T>(Guid id, string include) where T : class
{
    return _dbContext.Set<T>().Include(include).Find(id);
}

This will eagerly load one navigation property in my entity right.

But if my entity looks like this:

public class Blog : PrimaryKey
{
    public Author Author {get;set;}
    public ICollection<Post> Posts {get;set;}
}

How would I get eager loading for Author and Posts? Would I literally have to do:

_dbContext.Set<T>().Include("Author").Include("Posts").Find(id);

inevitably producing a function like this:

T EagerGetById<T>(Guid id, string include, string include2, string include3) where T : class
{
    return _dbContext.Set<T>().Include(include).Include(include2).Include(include3).Find(id);
}

Because that would be really inefficient for a Generic Repository!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you don't want to use strings, you can also do the same for any N number of includes by using an expression which returns the navigation properties to be eager loaded. (original source here)

public IQueryable<TEntity> GetAllIncluding(params Expression<Func<TEntity, object>>[] includeProperties) 
{
   IQueryable<TEntity> queryable = GetAll();
???foreach (Expression<Func<TEntity, object>> includeProperty in includeProperties) 
   {
???   queryable = queryable.Include<TEntity, object>(includeProperty);
???}

   return queryable;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...