Saturday, January 31, 2009

The pain of session variables in LINQ

Linq to Entities rocks. Seriously, but there are a few little bugbears.

One of them is in how errors are reported in a totally misleading manner.

Consider this little snippet of code.


var q=from t in MyEnities.SomeEntitySet
where t.ID==(int)Session["userid']
select t;

if (q.Count() > 0)


q.Count threw an exception that said:

LINQ to Entities does not recognize the method 'System.Object get_Item(System.String)' method, and this method cannot be translated into a store expression.

This drove me mad for hours because I tried everything such as verifying that the session existed, that the variable was real, was of the right type and was of the value I expected. All to no avail.

In the end I solved the problem by first saving the session value into a local variable which I then used in the LINQ expression.

It seems to me that this has to do with the order of how things are evaluated within a LINQ expression and may even constitute a bug in the language. Why? well because it seems obvious now that the direct value from the session variable is somehow used before the cast operation by the LINQ parser and so an exception that seems to have no real relation to actual circumstances is thrown.

I hope that this helps to trap similar errors for people hunting for hours on Google like I did.

8 comments:

Anonymous said...

Thanks mate, saved hours of searching and numerous braincells with this post. Luckily it's the first hit I got when searching for this error.

Axel said...

Thanks, Bob! Got caught too, but in a more subtle way: same binary worked fine on the Developement Fabric, but failed on Azure...

Unknown said...

This error also occurs when using a FormCollection value, or any reference type object. My belief is that the Linq expression does not resolve any objects other than basic values because those values could change at the time of execution (which works great for Linq to objects but not so well for Linq to SQL or Entities).

Dave Mackey said...

Thanks Bob! This was a huge help to me! I'm sure you saved me a few hours as well. :)

Anonymous said...

Many thanks for this one Bob. Saved me an awful lot of time

Anonymous said...

thanks Bob, this helped a lot... timesaver indeed

Anonymous said...

Thanks Bob!!! This was driving me crazy. Same issue using a session variable.

Anonymous said...

Thanks Bob!!! Same issue and it was driving me crazy!