假设我有一些看起来像这样的C#代码:
var query1 = query.Where(x => x.BirthDate > now);
var query2 = query.Where(x => x.EnrollmentDate > now);
var query3 = query.Where(x => x.GraduationDate > now);
实际代码更复杂,但我使用的是一个简单的例子。我将此代码传递给Entity Framework。
假设我看这个并说“这是非干的”,然后我写了这样的函数。
public IQueryable<Student> FilterAfterDate(IQueryable<Student> query,
Expression<Func<Student, DateTime>> GetDateExpression, DateTime now)
{
return query.Where(x => GetDateExpression(x) > now);
}
在运行时,这会产生以下错误:
The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.
我不知道细节,但我相信解决这个可能是以某种方式采取我的FilterAfterDate
这是Expression<Func<Student, DateTime>>
并以某种方式结合日期时间比较生成类型Expression<Func<Student, bool>>
的表达式传递给Where
函数,但我不知道该怎么做。
使用LINQKit,您可以编写您的方法(我更喜欢作为扩展方法),如下所示:
public static class StudentExt {
public static IQueryable<Student> FilterAfterDate(this IQueryable<Student> query,
Expression<Func<Student, DateTime>> GetDateExpression, DateTime now)
=> query.AsExpandable().Where(x => GetDateExpression.Invoke(x) > now);
}
并像这样使用它:
var q1 = query.FilterAfterDate(q => q.BirthDate, now);
var q2 = query.FilterAfterDate(q => q.EnrollmentDate, now);
var q3 = query.FilterAfterDate(q => q.GraduationDate, now);
要自己动手,你只需使用一个替代的常见ExpressionVisitor
:
public static class ExpressionExt {
/// <summary>
/// Replaces an Expression (reference Equals) with another Expression
/// </summary>
/// <param name="orig">The original Expression.</param>
/// <param name="from">The from Expression.</param>
/// <param name="to">The to Expression.</param>
/// <returns>Expression with all occurrences of from replaced with to</returns>
public static Expression Replace(this Expression orig, Expression from, Expression to) => new ReplaceVisitor(from, to).Visit(orig);
}
/// <summary>
/// ExpressionVisitor to replace an Expression (that is Equals) with another Expression.
/// </summary>
public class ReplaceVisitor : ExpressionVisitor {
readonly Expression from;
readonly Expression to;
public ReplaceVisitor(Expression from, Expression to) {
this.from = from;
this.to = to;
}
public override Expression Visit(Expression node) => node == from ? to : base.Visit(node);
}
现在,在Replace
可用的情况下,您可以创建一个lambda模板并使用它替换Expression
参数:
public static class StudentExt {
public static IQueryable<Student> FilterAfterDate(this IQueryable<Student> query,
Expression<Func<Student, DateTime>> GetDateExpression, DateTime now) {
Expression<Func<DateTime,bool>> templateFn = x => x > now;
var filterFn = Expression.Lambda<Func<Student,bool>>(templateFn.Body.Replace(templateFn.Parameters[0], GetDateExpression.Body), GetDateExpression.Parameters);
return query.Where(filterFn);
}
}
你使用它和LINQKit一样。