variable 'x' of type 'Product' referenced from scope, but it is not defined
Asked Answered
H

1

11

I have a class named Product in class library project. I am using SubSonic SimpleRepository to persist objects. I have a method as follows in Product class:

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

I'm calling this function like this:

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

Calling Load from BindData throws the exception:

variable 'x' of type 'Product' referenced from scope '', but it is not defined

How can I resolve this.

EDIT:- by stepping through SubSonic code I found that the error is thrown by this function

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);
}
Hettiehetty answered 12/1, 2011 at 19:45 Comment(1)
Looks like a bug in SubSonic. (@Kobi: No.)Toandfro
H
14

After banging my head on the wall for many days and even asking Jon Skeet for help, I found out the problem.

The problem actually is with SubSonic (@Timwi was right). It is right in this line:

var list = Product.Load(x => x.Active);//Active is of type bool

After I changed it to:

var list = Product.Load(x => x.Active==true);

all was well.

Hettiehetty answered 16/1, 2011 at 18:37 Comment(5)
Do you know why this was a problem?Expugnable
This is the top hit for the error message, unfortunately, as this isn't really an answer to the issue most are having, including me and @user1039462. For me, the issue was that you must use the same ParameterExpression everywhere. It is not enough that the ParameterExpression has the same variable name. I believed it was, but I'd get the exception about scope because I wasn't the same instance of ParameterExpression in my expression tree and in the root LambdaExpression.Degeneration
@Will the issue was in SubSonic. It was not setting the variable value if not explicitly set.Hettiehetty
@TheVillageIdiot: I know, but the error message is the same, and this question is the top hit for the error message :/Degeneration
I'm just leaving this comment here, since it's top hit for the error message. If you are using ServiceStack.OrmLite and have this exception trying to Select something from DB, please note that null check is properly done using NullableVar != null, not by NullableVar.HasValueSyncope

© 2022 - 2024 — McMap. All rights reserved.