2

I am trying to write an expression that invokes a method that accepts more than one argument as an input and this expression acts as a where clause to the nhibernate queryover engine. Currently I am getting an error saying:

System.Exception : Unrecognised method call: System.Func`3[[MyClass, Assembly, Version=9.123.434, Culture=neutral, PublicKeyToken=null],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=wjerkwr234],[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=234234123]]:Boolean Invoke(MyClass, Int32)

 Expression<Func<MyClass, int, bool>> restricton=
         (myClassObject, myNumber) => myClassObject.Property1== myNumber;

session
    .QueryOver<MyClass>()
    .Where(x =>x.Property2==1)
    .And(x=>restriction.Compile().Invoke(x, 2))

why am I using expression? Well that is a parameter to the function that generates the queryover statement and the condition there can change

Any idea what is wrong with the above code?

Julian
  • 20,008
  • 17
  • 77
  • 108
user917670
  • 873
  • 1
  • 11
  • 22

1 Answers1

7

the linq provider expects an Expression but you give it a Delegate because you use Compile().

int myNumber = 5;
Expression<Func<MyClass, bool>> restricton=
     myClassObject => myClassObject.Property1 == myNumber

session.QueryOver().Where(x => x.Property2 == 1).And(restriction)

Update: if it is only known when constructing the query

session.QueryOver().Where(x => x.Property2 == 1).And(CreateRestriction(2))

Expression<Func<MyClass, bool>> CreateRestriction(int myNumber)
{
    return myClassObject => myClassObject.Property1 == myNumber;
}
Firo
  • 30,626
  • 4
  • 55
  • 94
  • firo the problem is that myNumber cannot be set when I am constructing the Expression and that is why I had it as a second paramter.. whats the solution then? – user917670 Mar 06 '12 at 10:56