[英]The parameter '***' was not bound in the specified LINQ to Entities query expression
I am doing a common query in my project. 我正在我的项目中进行常见查询。 I use Expression to build my query tree, the code list below: 我使用Expression来构建我的查询树,代码列表如下:
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: 但是当我调用我的GetBooksFields
方法时,它会抛出一个异常,如下所示:
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. 我调试了expr变量并获得了正确的表达式:{ m => (m.Name == "sdf")
},这就是我想要的,但我不知道为什么我得到错误,thx。
You can't "trick" LINQ into interpreting parameters as member-expressions by throwing in dots into variable names. 你不能通过在变量名中加入点来“欺骗”LINQ将参数解释为成员表达式。
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.