参数' ***'未在指定的LINQ to Entities查询表达式中绑定 [英] The parameter '***' was not bound in the specified LINQ to Entities query expression

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

问题描述

我正在我的项目中进行常见查询.我使用Expression构建我的查询树,代码清单如下:

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变量,并获得了正确的表达式:{ m =>(m.Name =="sdf")},这正是我想要的,但是我不知道为什么会出现错误,谢谢.

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将参数解释为成员表达式.

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

您必须正确地构建表达式树,如下所示(根据您的评论将字段更改为属性):

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();          
}

这篇关于参数&amp;#39; ***&amp;#39;未在指定的LINQ to Entities查询表达式中绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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