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

10,413

You can never join objects from two different contexts; because the union is compiled into a database query, it wouldn't know how to execute it since multiple DB's are not supported. The best you can do is to call ToList() on each query separately, which will execute the database queries, and do a LINQ-to-Objects union. This is entirely an iterative process.

Share:
10,413

Related videos on Youtube

gan
Author by

gan

Updated on June 04, 2022

Comments

  • gan
    gan almost 2 years

    I have 2 var from same DBs, after union:

    var projectedP1 = P1.Select(x => new Project_test { 
                                         ID_inString = x.ID.ToString(), 
                                         col1 = x.col1, 
                                         col2 = x.col2, 
                                         col3 = x.col3 });
    var union = projectedP1.Union(P2);
    

    when P1 alone or P2 alone, everything is fine But when 2 is union, i get this in run-time:

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

    I tried this similar post, but dun understand. ANyone has any idea?

    The specified LINQ expression contains references to queries that are associated with different contexts

    • gan
      gan over 12 years
      Thanks for clarification, LINQ sounds like weird to me
    • Jon Skeet
      Jon Skeet over 12 years
      Well ignoring the LINQ part of things, how would you suggest running a single query using data from two different databases?
  • Jon Skeet
    Jon Skeet over 12 years
    You don't need to call ToList - just AsEnumerable will do: P1.AsEnumerable().Union(P2).
  • Brian Mains
    Brian Mains over 12 years
    Thanks for the tip... You'd also have to do it on P2 because that would have to be executed against its context, would it not? I guess here since it's the second resultset, not executed within the context of the first operation, it would pass through fine and wouldn't attempt to translate the union as part of its query...
  • Jon Skeet
    Jon Skeet over 12 years
    No, you don't have to do it on P2 because just doing it on P1 means it'll use the implementation in Enumerable, treating P1 as an IEnumerable<T> already.