【问题标题】:LINQ Expression Tree - The parameter 'x' was not bound in the specified LINQ to Entities query expressionLINQ 表达式树 - 参数“x”未绑定在指定的 LINQ to Entities 查询表达式中
【发布时间】:2019-05-16 15:22:12
【问题描述】:

我正在尝试动态构建表达式树以从数据库中获取数据。

以下代码用于此。

Expression<Func<Client, bool>> expression = x => true;
foreach (var item in searchParams)
{
    var operatorType = ExpressionType.Equal;
    string propertyName = null;
    object value = null;
    string keyValue = item.Value;

    if (item.Key == Constants.SearchParameterNames.Id)
    {
        int val = 0;
        if (int.TryParse(keyValue, out val))
            value = val;
        propertyName = "ClientID";
    }
    else if (item.Key == Constants.SearchParameterNames.Lastupdate)
    {
        DateTime dateTime;
        if (DateTime.TryParse(keyValue, out dateTime))
            value = dateTime;
        propertyName = "LastChange";
    }

    if (!string.IsNullOrWhiteSpace(propertyName) && value != null)
    {

            var exp = GetBinaryOperation<Client>(propertyName, operatorType, value);
            var exp1 = Expression.And(expression.Body, exp);
            expression = Expression.Lambda<Func<Client, bool>>(exp1, expression.Parameters);
    }

}
var client = _clientRepository.FindBy(expression).ToList();

_clientRepository.FindBy(expression).ToList() 被执行时,我遇到了一个异常

参数“x”未绑定在指定的 LINQ to Entities 中 查询表达式。

用于创建表达式的方法:

public BinaryExpression GetBinaryOperation<T>(string propertyName, ExpressionType type, object value)
{

    var parameterExpression = Expression.Parameter(typeof(T), "x");
    var memberExpression = Expression.Property(parameterExpression, propertyName); 
    var propertyType = GetMemberType(memberExpression);
    var rhs = Expression.Constant(value);
    var binaryExpression = Expression.MakeBinary(type, memberExpression, rhs);

    return binaryExpression; 
}

【问题讨论】:

  • 除了 Zoltán 的回答之外,您应该用逻辑和 (Expression.AndAlso) 替换通常用于数字的二进制和 (Expression.AndAlso),考虑到您有一个谓词表达式树。

标签: c# entity-framework linq expression-trees


【解决方案1】:

在构建这样的表达式时,您必须保留顶级参数表达式实例。当您在 GetBinaryOperation 函数中创建一个新参数表达式时,这将是一个不同的实例(因此是 not bound 术语),而不管它的名称是同一个"x"

您应该将原始LambdaExpression"x" 参数传递给GetBinaryOperation 函数,而不是创建新的参数实例,例如使用expression.Parameters[0]

总而言之,在这种情况下,您必须在整个表达式树中使用same parameter expression instance

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-19
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    相关资源
    最近更新 更多