从作用域引用的'Product'类型的变量'x',但未定义

The*_*iot 11 c# lambda subsonic3 linq-expressions

我有一个Product在类库项目中命名的类.我SubSonic SimpleRepository用来坚持对象.我在Product课堂上有如下方法:

public static IList<Product> Load(Expression<Func<Product, bool>> expression)
{
    var rep=RepoHelper.GetRepo("ConStr");
    var products = rep.Find(expression);
    return products.ToList();
}
Run Code Online (Sandbox Code Playgroud)

我正在调用这个函数:

private void BindData()
{
    var list = Product.Load(x => x.Active);//Active is of type bool
    rptrItems.DataSource = list;
    rptrItems.DataBind();
}
Run Code Online (Sandbox Code Playgroud)

调用LoadBindData引发异常:

variable 'x' of type 'Product' referenced from scope '', but it is not defined
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题.

编辑: - 通过单步执行SubSonic代码,我发现该函数抛出了错误

private static Expression Evaluate(Expression e)
{
    if(e.NodeType == ExpressionType.Constant)
        return e;
    Type type = e.Type;
    if(type.IsValueType)
        e = Expression.Convert(e, typeof(object));
    Expression<Func<object>> lambda = Expression.Lambda<Func<object>>(e);
    Func<object> fn = lambda.Compile(); //THIS THROWS EXCEPTION
    return Expression.Constant(fn(), type);
}
Run Code Online (Sandbox Code Playgroud)

The*_*iot 13

在我的头撞墙多日,甚至向Jon Skeet寻求帮助后,我发现了问题所在.

问题实际上是SubSonic(@Timwi是对的).这是正确的:

var list = Product.Load(x => x.Active);//Active is of type bool
Run Code Online (Sandbox Code Playgroud)

我把它改成后:

var list = Product.Load(x => x.Active==true);
Run Code Online (Sandbox Code Playgroud)

一切都好.

  • 你知道为什么这是一个问题吗? (5认同)
  • 不幸的是,这是错误消息的最高点,因为这不是大多数问题的答案,包括我和@ user1039462.对我来说,问题是你必须在任何地方*使用相同的ParameterExpression*.参数表达式具有相同的变量名称是不够的**.我相信它是,但我得到关于范围的例外,因为我在表达式树和根LambdaExpression中不是ParameterExpression的同一个实例. (3认同)
  • 我只是将这条评论留在这里,因为它是错误消息的热门评论。如果您使用 ServiceStack.OrmLite 并在尝试从数据库中“Select”某些内容时遇到此异常,请注意,空检查是使用“NullableVar != null”而不是“NullableVar.HasValue”正确完成的 (2认同)