“***”在指定的LINQ到实体未绑定的参数查询EX pression [英] The parameter '***' was not bound in the specified LINQ to Entities query expression

查看:346
本文介绍了“***”在指定的LINQ到实体未绑定的参数查询EX pression的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做我的项目中常见的查询。我用防爆pression建立我的查询树,低于code清单:

I am doing a common query in my project. I use Expression to build my query tree, the code list below:

 public IList<Book> GetBooksFields(string fieldName, string fieldValue)
    {
        ParameterExpression paramLeft = Expression.Parameter(typeof(string), "m." + fieldName);
        ParameterExpression paramRight = Expression.Parameter(typeof(string), "\"" + fieldValue + "\"");

        ParameterExpression binaryLeft = Expression.Parameter(typeof(Book),"m");
        BinaryExpression binaryExpr = Expression.Equal(paramLeft, paramRight);

        var expr = Expression.Lambda<Func<Book, bool>>(binaryExpr, binaryLeft);

        return bookRepository.GetMany(expr).ToList();

    }

但是,当我调用我的 GetBooksFields 方法,它将如下扔给我一个例外:

But when I invoke my GetBooksFields method, it will throw me an exception as below:

我调试的expr的变量,并得到了正确的EX pression:{M =&GT <$ C C $>; (m.Name ==自卫队)},这是我想要的,但我不知道为什么我得到了错误,THX。

I debugged the expr variable and got the correct expression: {m => (m.Name == "sdf")}, it was what I want, But I don't know why I got the error,thx.

推荐答案

您不能绝招LINQ到跨preting参数成员-EX pressions被扔在点到变量名。

You can't "trick" LINQ into interpreting parameters as member-expressions by throwing in dots into variable names.

您将必须正确构造前pression树,如下图 (编辑:改变字段属性根据您的评论):

You'll have to construct the expression-tree correctly, as below ( changed field to property as per your comment):

public IList<Book> GetBooksFields(string propertyName, string propertyValue)
{
     var parameter = Expression.Parameter(typeof(Book), "book");

     var left = Expression.Property(parameter, propertyName);   

     var convertedValue = Convert.ChangeType
                          ( 
                              propertyValue, 
                              typeof(Book).GetProperty(propertyName).PropertyType
                          );

     var right = Expression.Constant(convertedValue);

     var binaryExpr = Expression.Equal(left, right);        
     var expr = Expression.Lambda<Func<Book, bool>>(binaryExpr, parameter);     

     return bookRepository.GetMany(expr).ToList();          
}

这篇关于“***”在指定的LINQ到实体未绑定的参数查询EX pression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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