我在这个时候我有存储库充满了多个获取方法。EF发送包含列表到存储库通过参数
E.q. Get1() => cxt.Entites.Include(e => e.obj1); Get2() => cxt.Entities.Include(e => e.obj1).Include(e => e.obj2)
依此类推。
有没有好的方法,模式有一个GET方法,我可以通过参数发送inclues?
我在这个时候我有存储库充满了多个获取方法。EF发送包含列表到存储库通过参数
E.q. Get1() => cxt.Entites.Include(e => e.obj1); Get2() => cxt.Entities.Include(e => e.obj1).Include(e => e.obj2)
依此类推。
有没有好的方法,模式有一个GET方法,我可以通过参数发送inclues?
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
见msdn 库模式您可以使用
_sampleRepostiory.Get(h=>h.Id>1,null,"Employees.Departments");
包括同与拉姆达
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
Expression<Func<TEntity, object>>[] includes)
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
if (includes != null)
{
query = includes.Aggregate(query,
(current, include) => current.Include(include));
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
消耗它这样
var query = context.Customers
.Get(x=>x.Id>1,null,
c => c.Address,
c => c.Orders.Select(o => o.OrderItems));
我确实在我的项目如下:
public Entity[] GetAll(bool includeObj1, bool includeAllOthers) {
IQueryable<Entity> entity = ctx.Entities;
if (includeObj1)
entity = entity.Include(e => e.obj1);
if (includeAllOthers) {
entity = entity
.Include(e => e.obj2)
.Include(e => e.obj3)
.Include(e => e.obj4)
.Include(e => e.obj5);
}
return entity.ToArray();
}
像includeObj1
和includeObj2
提供了论据从实现中分离出库的消费者和封装任何数据访问逻辑。
直接传递“包含这些属性”命令到存储库意味着您知道存储库的工作方式,并假定它是某种排除抽象的ORM。
不,不好。我有很多要包含的对象。所以我不想用7+参数的方法。 – Nerf
@Nerf比7+方法具有相似的内容更好。如果您需要一种根据7种可能的状态选项返回不同结果的方法,那么可以预期有7个参数。 –
使用此方法的人必须知道并列举所有包含的属性。如果有人决定更改属性名称,那么他应该通过项目Ctrl + Shift + F并更改所有文本用法。如果有人添加一个应该包含在eveyrwhere中的属性,那么他应该找到所有用法,并为每个字符串添加“,NewProperty”。听起来像SRP侵犯。我不能相信像[tdykstra](https://github.com/tdykstra)这样的人可以编写错误的代码,所以应该有一些我不明白的东西,这让我感到很难过: –
我把代码是在msdn。我已经做了一个重载的方法是使用lamda表达式,你不需要使用字符串。请参阅https://stackoverflow.com/questions/5376421/ef-including-other-entities- generic-repository-pattern – Eldho
它引发参数null异常;/ – Nerf