实体框架加载所有导航属性 [英] EntityFramework Eager Load all Navigation Properties
问题描述
我已经在我的存储库中创建了一个函数:
$ b $其中T:class
{
返回_dbContext.Set< T>()。包含((id)包括).Find(ID);
}
这将真正加载我的实体中的一个导航属性。
但如果我的实体看起来像这样:
public class Blog:PrimaryKey
{
public作者作者{get; set;}
public ICollection< Post>帖子{get; set;}
}
我将如何加载作者
和帖子
?我真的要做:
_dbContext.Set&T;()。Include(Author)。帖子)找到(ID)。
不可避免地产生这样的功能:
T EagerGetById< T>(Guid id,string include,string include2,string include3)其中T:class
{
return _dbContext.Set&T; .INCLUDE(包括).INCLUDE(include2).INCLUDE(include3).Find(ID);
}
因为对于 Generic
Repository!
如果你不想使用字符串,你也可以这样做通过使用返回导航属性的表达式来加载任何N个包含。 (原始来源此处)
public IQueryable< TEntity> GetAllIncluding(params Expression< Func< TEntity,object>> [] includeProperties)
{
IQueryable< TEntity> queryable = GetAll();
foreach(表达式 {
queryable = queryable.Include< TEntity,object>(includeProperty);
}
返回可查询;
}
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!
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;
}
这篇关于实体框架加载所有导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!