将Lambda作为参数传递给EFCore中的存储库方法

时间:2016-07-07 15:53:33

标签: asp.net-core entity-framework-core

我正在尝试按照here

所述实现存储库模式

然而,这些关系并未包括在内。

public IEnumerable<MyEntity> GetWithRelationship(params Expression<Func<MyEntity, object>>[] includeProperties)
{
  var set = _context.MyEntities;
  foreach (var includeProperty in includeProperties)
  {
    set.Include(includeProperty);
  }
  return set.ToList();
}

然而,以下工作:

return _context.MyEntities.Include(x => x.RelatedEntity).ToList();

1 个答案:

答案 0 :(得分:2)

您必须将set重新分配给Include()方法的返回值。但是,为了避免编译错误,您必须先将set视为IQueryable<MyEntity>

var set = _context.MyEntities as IQueryable<MyEntity>;

foreach (var includeProperty in includeProperties)
{
    set = set.Include(includeProperty);
}

return set.ToList();