tags:

views:

40

answers:

1

I'm getting this error when using LINQ2SQL:

The query contains references to items defined on a different data context.

Here's the code:

    var instances = (from i in context.List
                     join j in context.CatsList on i.ListID equals j.ListID
                     join c in context.Cats on j.CatID equals c.CatID
                     where c.SID == Current.SID
                     orderby i.Title
                     select i).Distinct();

The problem, as far as I can ascertain, is that the Current object is actually a LINQ2SQL object returned from a property executing a different LINQ statement.

So, therefore, LINQ2SQL doesn't like executing a query on the database where the query has to be built from one LINQ statement including another statement's result.

My problem with that is that (I'll try to summarise the issue here) the Current object is retrieved using the same context as the query above and ultimately the Current.SID should simply resolve to an int, so what is the compiler's problem with executing it?

In short, why is it not possible to execute a LINQ query using a previous query's returned object as an argument?

A: 

This is a solution to the issue, rather than a direct answer of your final question, but you can probably get by with:

var sid = Current.SID;
var instances = (from i in context.List
                 join j in context.CatsList on i.ListID equals j.ListID
                 join c in context.Cats on j.CatID equals c.CatID
                 where c.SID == sid
                 orderby i.Title
                 select i).Distinct();
kbrimington
Yes, that's what I thought. And that was my first investigation while writing the original question. But no, I'm getting the same error. As far as I can see, the only elements involved in the query are i, j and c - all taken from the one context. So what is it really complaining about?
Matt W
Does it work if you swap out `equals` for `==`?
kbrimington
No, compiler error states "Expected contextual keyword 'equals'" and "The name 'j' is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'."
Matt W
Found it. Lets call this one "user error". I was referencing the context as a property (yes, I know, bad naming convention there) and it was constructing a new instance of the LINQ context on every reference, so each from and join had a different SQL context to contend with! This is now storing the once context object and re-using it. D'oh!
Matt W
Ah. Good work tracking it down.
kbrimington