13

I have two tables from two different Data Contexts. Although both tables are from the same database, two separate datacontexts exist.

Error message:

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

How can I get around this? Any help is appreciated. Thanks.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
jinsungy
  • 10,717
  • 24
  • 71
  • 79
  • 1
    How does it make sense from a business standpoint to have 2 datacontexts? Normally I would recommend to always have just 1 datacontext per database and work with that... – Robban Oct 08 '09 at 13:43
  • 2
    It probably doesn't make sense, but this is what I'm working with. – jinsungy Oct 08 '09 at 14:08
  • Its good practice to have one context for read and one for write – skyfoot Mar 21 '12 at 13:42

3 Answers3

7

If your code does something along the lines of:

from a in dc1.TableA
join b in dc2.TableB on a.id equals b.id
select new { a, b }

...just change it to:

from a in dc1.TableA
join b in dc1.GetTable<TableB>() on a.id equals b.id
select new { a, b }

The L2S datacontext uses the attributes on the class, so if you use GetTable on another datacontext than the one the table is attached to it will just pick up the table, column, etc attributes from the class def and use it as if it was part of the DC you're using in the query...

KristoferA
  • 12,287
  • 1
  • 40
  • 62
2

You don't. The data contexts may have inconsistent views of the database.

Greg D
  • 43,259
  • 14
  • 84
  • 117
2

Another solution is change the result to List().

var query = (from a in dc1.TableA 
            join b in dc2.TableB on a.id equals b.id 
            select new { a, b }).ToList()
Cyberpks
  • 1,401
  • 6
  • 21
  • 51
Henry
  • 21
  • 1