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

.net c# expression expression-trees linq

Question

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

    }

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

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.

1
6
4/11/2014 4:42:13 AM

Accepted Answer

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 (EDIT: 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();          
}
6
4/11/2014 5:03:26 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow