EntityFramework Eager加载所有导航属性

Cal*_*ton 14 c# entity-framework

我正在使用DI和IoC的Repository模式.

我在我的存储库中创建了一个函数:

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

这将急切地在我的实体中加载一个导航属性.

但如果我的实体看起来像这样:

public class Blog : PrimaryKey
{
    public Author Author {get;set;}
    public ICollection<Post> Posts {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

我将如何获得渴望装载AuthorPosts?我真的必须这样做:

_dbContext.Set<T>().Include("Author").Include("Posts").Find(id);
Run Code Online (Sandbox Code Playgroud)

不可避免地产生这样的功能:

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);
}
Run Code Online (Sandbox Code Playgroud)

因为这对于Generic存储库来说效率非常低!

Dan*_*ger 25

如果您不想使用字符串,则还可以通过使用返回要急切加载的导航属性的表达式对任何N个包含执行相同操作.(原始来源这里)

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;
}
Run Code Online (Sandbox Code Playgroud)