我想简化代码以添加加载选项和关联过滤,所以我创建了这个类。
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 表达式