在我用C#编写的项目中,我发现了一个用于linq方法的巨大谓词:
public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate);
这个谓词运作得很完美,但它在很多条件下我在理解它之前经常挣扎。我想让它变得可读。所以我写了几个表达式。
但我有一个像这样的运行时异常:The dreaded "parameter was not bound in the specified LINQ to Entities query expression" exception
我想尝试答案,但我仍然不明白为什么参数(c)有问题请看:
// in a method
Func<string, Expression<Func<TEntity, bool>>> expr1 = (query) => return (c) => ... ;
Func<string, Expression<Func<TEntity, bool>>> expr2 = (query) => return (c) => ... ;
var expr = Expression.AndAlso(expr1("a string").Body, expr2("same string").Body);
return Expression.Lambda<Func<TEntity, bool>>(expr , expr1("a string").Parameters[0]);
我的问题是理解为什么会发生这种异常,最后我又回到了巨大的谓词。
答案 0 :(得分:2)
因为您看到一个c
参数,实际上有两个不同的c
参数(让他们称之为c1
和c2
)。因此,当您合并两个表达式时:
c1 => c1.Something && c2.SomethingElse;
CLR生气,因为它无法找到c2
。
更糟糕的是,在您编写代码时,您有三 c
!
c3 => c1.Something && c2.SomethingElse
这是因为您重建expr1("a string")
两次(在Expression.AndAlso(expr1("a string").Body
和expr1("a string").Parameters[0]
中)!
你应该保存它!
var temp1 = expr1("a string");
var temp2 = expr2("same string");
var expr = Expression.AndAlso(temp1.Body, temp2.Body);
// now fix the expr so that it uses the parameters of temp1
return Expression.Lambda<Func<TEntity, bool>>(expr, temp1.Parameters);
举一个明确的例子:
var temp1a = expr1("a string");
var temp1b = expr1("a string");
var temp2 = expr2("same string");
Console.WriteLine(temp1a.Parameters[0] == temp1b.Parameters[0]); // False
Console.WriteLine(temp1a.Parameters[0] == temp2.Parameters[0]); // False
现在......我的参数替代品版本:
public class SimpleParameterReplacer : ExpressionVisitor
{
public readonly ReadOnlyCollection<ParameterExpression> From;
public readonly ReadOnlyCollection<ParameterExpression> To;
public SimpleParameterReplacer(ParameterExpression from, ParameterExpression to)
: this(new[] { from }, new[] { to })
{
}
public SimpleParameterReplacer(IList<ParameterExpression> from, IList<ParameterExpression> to)
{
if (from == null || from.Any(x => x == null))
{
throw new ArgumentNullException("from");
}
if (to == null || to.Any(x => x == null))
{
throw new ArgumentNullException("to");
}
if (from.Count != to.Count)
{
throw new ArgumentException("to");
}
// Note that we should really clone from and to... But we will
// ignore this!
From = new ReadOnlyCollection<ParameterExpression>(from);
To = new ReadOnlyCollection<ParameterExpression>(to);
}
protected override Expression VisitParameter(ParameterExpression node)
{
int ix = From.IndexOf(node);
if (ix != -1)
{
node = To[ix];
}
return base.VisitParameter(node);
}
}
您可以使用更改单个参数或参数数组...您可以使用它:
var temp1 = expr1("a string");
var temp2 = expr2("same string");
var expr = Expression.AndAlso(temp1.Body, temp2.Body);
expr = new SimpleParameterReplacer(temp2.Parameters, temp1.Parameters).Visit(expr);
return Expression.Lambda<Func<TEntity, bool>>(expr, temp1.Parameters);