![](/img/trans.png)
[英]EntityFramework Core: Eager loading navigation properties of derived types
[英]EntityFramework Eager Load all Navigation Properties
我正在使用DI和IoC的Repository模式。
我在我的存储库中创建了一个函数:
T EagerGetById<T>(Guid id, string include) where T : class
{
return _dbContext.Set<T>().Include(include).Find(id);
}
这将急切地在我的实体中加载一个导航属性。
但如果我的实体看起来像这样:
public class Blog : PrimaryKey
{
public Author Author {get;set;}
public ICollection<Post> Posts {get;set;}
}
我如何获得Author
和Posts
热切加载? 我真的必须这样做:
_dbContext.Set<T>().Include("Author").Include("Posts").Find(id);
不可避免地产生这样的功能:
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);
}
因为对于Generic
Repository来说,这实际上是非常低效的!
如果您不想使用字符串,则还可以通过使用返回要急切加载的导航属性的表达式对任何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;
}
如果您需要所有导航属性,则别无选择,只能从数据库中读取所有这些属性。 您可以在查询中Include
它们,也可以事先将它们读取到DbSet的本地数据中。
如果要将多个包含传递给方法,只需将其定义如下:
T EagerGetById<T>(Guid id, params string[] includes)
您的用户将能够调用EagerGetById(id, "inc1", "inc2", ...)
在您的方法中,只需为includes
数组中的每个元素调用Include
。
你应该准备好关于params
关键字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.