组合AndAlso参数“foo”未绑定到指定的LINQ to Entities查询表达式中 [英] Combining AndAlso The parameter 'foo' was not bound in the specified LINQ to Entities query expression

查看:113
本文介绍了组合AndAlso参数“foo”未绑定到指定的LINQ to Entities查询表达式中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体。

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
}

我想创建自己的表达式谓词。为此,我创建了一个接受属性名称和值的方法。

I want to create my own expression predicate. For that I have created a method that accepts property name and the value.

private static Expression<Func<Foo, bool>> Condition(string pName, object value)
{
    var pe = Expression.Parameter(typeof(Foo), "foo");
    var left = Expression.Property(pe, pName);
    var right = Expression.Constant(value);
    var equal = Expression.Equal(left, right);
    var predicate = Expression.Lambda<Func<Foo, bool>>(equal, pe);
    return predicate;
}

这是对单个条件工作正常的谓词。

This is the predicate which works fine for a single condition.

using (var db = new MyEntities())
{
    var predicate = Condition("Name", "foo");
    var foos = db.Foos.Where(predicate).ToArray();
}

但是当我尝试通过以下方式组合两个条件:这篇文章,它会抛出异常。

But when I tried to combine two conditions by following this post, it throws exception.


参数'foo'未在指定的LINQ to Entities
查询表达式中绑定。

The parameter 'foo' was not bound in the specified LINQ to Entities query expression.



using (var db = new MyEntities())
{
    var cond1 = Condition("Name", "foo");
    var cond2 = Condition("Code", "bar");
    var body = Expression.AndAlso(cond1.Body, cond2.Body);
    var predicate = Expression.Lambda<Func<Foo,bool>>(body, cond1.Parameters[0]);
    var foos = db.Foos.Where(predicate).ToArray(); // exception
}

请启发我。

推荐答案

问题是LINQ表达式中的 ParameterExpression 通过引用相等来标识,但两个参数对象是不同的引用。 (中的名称参数表达式仅存在用于调试目的)。

The problem is that ParameterExpression in LINQ expressions is identified by reference equality, but the two Parameter objects are different references. (The name in ParameterExpression only exists for debugging purposes).

(如果您重读了上述帖子,则表示您尝试的方法仅在两个lambdas在同一个 ParameterExpression 对象上定义)时才起作用。

(If you reread the mentioned post, it says that the method that you tried would only work if both lambdas are defined on the same ParameterExpression object).

在这个阶段你有两大可能性:您可以为 Condition 函数定义一种方式来接受 ParameterExpression 对象,或者创建一个 ExpressionVisitor ,将代替原始的 ParameterExpression 另一个。 (当然,考虑到你想做一个 AndAlso ,你也可以想象地连接两个 Where 子句,但是不太普遍。)

You have two big possibilities at this stage: either you define a way for the Condition function to accept a ParameterExpression object, or you create an ExpressionVisitor that will replace the original ParameterExpression with another. (Of course, given that you want to do an AndAlso, you could also conceivably chain two Where clauses, but that is less general.)

这篇关于组合AndAlso参数“foo”未绑定到指定的LINQ to Entities查询表达式中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆