在EF6中,获取DbSet对象的所有子节点的最有效方法是什么,DbSet对象可以有子节点且子节点位于ICollection
?
这是我的班级:
public class Simple
{
[Key]
public int id { get; set; }
public int? simpleId { get; set; }
[ForeignKey("simpleId")]
public virtual Simple simple { get; set; }
public virtual ICollection<Simple> simpleObjects { get; set; }
}
以下是我的一些代码:
public IQueryable<Simple> GetAll(params Expression<Func<Simple, object>>[] includeExpressions)
{
IQueryable<Simple> set = db.Simple;
foreach (var includeExpression in includeExpressions)
{
set = set.Include(includeExpression);
}
return set;
}
我使用以下代码调用该函数:
IQueryable<Simple> getAll = GetAll(o=> o.simpleObjects);
这将返回DbSet中的所有Simple
个对象。
如何获取特定Simple
对象的所有子节点,其中我有Simple
个对象,而不是整个DbSet中的所有Simple
个对象?
答案 0 :(得分:1)
我不确定这是你想要的,但它可能会有所帮助。
public IQueryable<TEntity> GetItems(Expression<Func<TEntity, bool>> predicate, params Expression<Func<TEntity, object>>[] includeProperties)
{
var query = predicate == null
? dbContext.EntitySet<TEntity>()
: dbContext.EntitySet<TEntity>().Where(predicate);
if (includeProperties != null)
query = ApplyIncludesOnQuery(query, includeProperties);
return query;
}
public IQueryable<TEntity> ApplyIncludesOnQuery(IQueryable<TEntity> query, params Expression<Func<TEntity, object>>[] includeProperties)
{
//Return Applied Includes query
return (includeProperties.Aggregate(query, (currentEntity, navigation) => currentEntity.Include(navigation)));
}
全部导航
var allItesm = GetItems<Simple>(null, s => s.simpleObjects)
通过导航获取特定信息
var item = GetItems<Simple>(s => s.Id == someId, s => s.simpleObjects)
无需导航即可获取特定内容
var item = GetItems<Simple>(s => s.Id == someId)