var predicate = PredicateBuilder.True<Document>();
predicate = predicate.And<Document>(User.SubQuery("UserName", "DAVER"));
predicate = predicate.And<Document>(AdHoc<Document>("OwnerId", 1));
var finDocs = docs.AsQueryable().Where(predicate).ToList();
我有一个使用此方法的扩展类:
public static Expression<Func<T, bool>> AdHoc<T>
(string columnName, object compValue)
{
// Determine type of parameter
ParameterExpression parameter = Expression.Parameter(typeof(T), "x");
// Target to compare to
Expression property = Expression.Property(parameter, columnName);
// The value to match
Expression constant = Expression.Constant(compValue, compValue.GetType());
Expression equality = Expression.Equal(property, constant);
Expression<Func<T, bool>> predicate =
Expression.Lambda<Func<T, bool>>(equality, parameter);
return predicate;
}
在我的用户类中,我有一个静态方法:
public static Expression<Func<Document, bool>> SubQuery(string property,
string targetValue)
{
var predicate = PredicateBuilder.True<User>();
predicate = predicate.And<User>(Extensions.AdHoc<User>(property, targetValue));
Expression<Func<Document, bool>> userSelector =
doc => doc.Users
.AsQueryable()
.Any(predicate);
var docParm = Expression.Parameter(typeof(Document), "appDoc");
var body = Expression.Invoke(userSelector, docParm);
var docPredicate = PredicateBuilder.True<Document>();
docPredicate = docPredicate.And<Document>(Expression.Lambda<Func<Document, bool>>(body, docParm));
return docPredicate;
}
缺点是我在用户类本身中包含了子查询功能。它完成了任务,但如果有人有任何建议或更好的方法来使用泛型,这样我就不必在我的用户类中包含这个静态方法,我很想听听你的意见。