【发布时间】:2013-05-30 11:02:00
【问题描述】:
我想简化代码以添加加载选项和关联过滤,所以我创建了这个类。
class GraphQuery<T>
{
private IQueryable<T> query;
private DataLoadOptions load;
public GraphQuery(DataLoadOptions load, IQueryable<T> query)
{
this.load = load;
this.query = query;
}
public GraphQuery<T> Load(
Expression<Func<T, object>> expr,
Expression<Func<T, object>> filter)
{
load.LoadWith(expr);
load.AssociateWith(filter);
return this;
}
// more public methods ...
}
然后可以这样使用:
var clients = Graph(db.Clients.Where(e => !e.Deleted))
.Load(e => e.ClientPersons,
e => e.ClientPersons.Where(j => !j.Person.Deleted));
但是,我看到 e => e.ClientPersons 的一个非常简单的重复。所以我想将上述用法减少到:
var clients = Graph(db.Clients.Where(e => !e.Deleted))
.Load(e => e.ClientPersons.Where(j => !j.Person.Deleted));
所以 Load 函数应该看起来像
public GraphQuery<T> Load(Expression<Func<T, object>> filter)
{
var expr = ... extract first part of the expression that represents the association property
load.LoadWith(expr);
load.AssociateWith(filter);
return this;
}
除了在查询中使用之外,我从未使用过 linq 表达式
【问题讨论】:
标签: c# linq linq-to-sql lambda expression