Error when using the WHERE clause in Linq to SQL

I have a datacontext that I'm trying to query, the results of which I want to bind to a gridview on a button click. Getting connected to the datacontext works great. I get the 1000s of records I expect. When I try to add the WHERE clause, I run into problems. Here's the button event I'm trying to make it happen at:

Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs)         
      Dim dsource = New MY_DataContext().SV_XXXs '--- This works, the data is all there        
      gridRec.DataSource = dsource.ToList().Where(Function(dtable) dtable.PN = Session("PN"))   '--- this fails
      '--- Also tried this, it also did not work ----------------------------------------------------------
      '--- gridRec.DataSource = dsource.Where(Function(dtable) dtable.PN = Session("PN"))   '--- this fails
End Sub

The session variable is valid and the dsource is populating correctly, but I get the following error when it tries to execute the Where clause:

Evaluation of method System.Linq.SystemCore_EnumerableDebugView`1[SV_REC].get_Items() calls into native method System.WeakReference.get_Target(). Evaluation of native methods in this context is not supported.

Also tried:

Dim results =
            From T In dsource
            Where T.PN = Session("SAFRReceiverPN")
            Select T

And get this error

Method 'System.Object CompareObjectEqual(System.Object, System.Object, Boolean)' has no supported translation to SQL.

And tried:

Dim results = From t In dsource Where (t.PN = Session("SAFRReceiverPN")) Select t

nothing seems to work for me when trying a WHERE clause

C# or VB.NET are both cool if you have any suggestions. Really, any help is appreciated, thanks.

Jon Skeet

LINQ to SQL doesn't know what to do when you try to access the session inside the query. Instead of doing that, fetch the value from the session before the query and store the result in a local variable, then use that local variable in your query. For example, in C#:

var receiver = (string) Session["SAFRReceiverPN"];
var results = dsource.Where(t => t.PN == receiver);

(I don't bother with query expressions when you're just trying to perform a simple filter.)


See more on this question at Stackoverflow