的EntityFramework贪婪加载所有的导航属性 [英] EntityFramework Eager Load all Navigation Properties
问题描述
我使用的是与DI和IOC Repository模式
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);
}
由于这将是一个通用<真低效/ code>库!
Because that would be really inefficient for a Generic
Repository!
感谢
推荐答案
如果你不想使用字符串,你也可以做同样的任何N多的使用返回导航性能急于加载一个表达式包含。 (原始来源这里)
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;
}
这篇关于的EntityFramework贪婪加载所有的导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!