6

Does anyone know of any way to overcome NotSupportedException? I have a method against a User:

 public virtual bool IsAbove(User otherUser)
 {
     return HeirarchyString.StartsWith(otherUser.HeirarchyString);
 }

And I want to do:

_session.Query<User>.Where(x => loggedInUser.IsAbove(x));

But this throws a NotSupportedException. The real pain though is that using

_session.Query<User>.Where(x => loggedInUser.HeirarchyString.StartsWith(x.HeirarchyString));

works absolutely fine. I don't like this as a solution, however, because it means that if I change how the IsAbove method works, I have to remember all the places where I have duplicated the code whenever I want to update it

Jordan Wallwork
  • 3,116
  • 2
  • 24
  • 49

1 Answers1

3

Name the specification expression and reuse that, e.g:

public Expression<Func<....>> IsAboveSpecification = (...) => ...;

public virtual bool IsAbove(User otherUser)
{
    return IsAboveSpecification(HeirarchyString, otherUser.HeirarchyString);
}

Reuse IsAboveSpecification in the query as needed. If the IsAbove() method is used often use can cache the result of the Compile() method on the expression.

Oskar Berggren
  • 5,583
  • 1
  • 19
  • 36
  • I'm having the same issue as OP. Can't get this solution to work. In the first place, I want to be able to call on the object, so I had to move the initialization into the constructor because `this` was not available in a member initializer. Worse, I'm getting an error when trying to call the specification expression: "Method, delegate or event expected". Any suggestions? – Josh G Dec 19 '13 at 20:24
  • Tried calling .Compile().Invoke() on the expression. It compiles now, but getting the same exception when calling the function "IsAbove" from a query. – Josh G Dec 19 '13 at 20:27
  • Can't call the expression from the query for several reasons: first, when it is marked as public, NH complains that fields must be protected or private. Second, when I tried calling it from an external query I got the same "Method, delegate or event expected" compiler error as above. – Josh G Dec 19 '13 at 20:28
  • You should ask a new question and post the code you are attempting to use. I don't think NH would complain about something being public - it does insist that the `virtual` modifier is present though. – Oskar Berggren Dec 21 '13 at 23:15
  • Thanks for the suggestion. Kind of moved on for the moment, but I'm sure we will come back to this. I'll ask a new question when this becomes relevant again (it will!). – Josh G Jan 06 '14 at 13:36