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

c# entity-framework linq

Question

Here's my code:

var myStrings = (from x in db1.MyStrings.Where(x => homeStrings.Contains(x.Content))
                    join y in db2.MyStaticStringTranslations on x.Id equals y.id
                    select new MyStringModel()
                    {
                        Id = x.Id,
                        Original = x.Content,
                        Translation = y.translation
                    }).ToList();

And I get the error that the specified LINQ expression contains references to queries that are associated with different contexts. I know that the problem is that I try to access tables from both db1 and db2, but how do I fix this?

1
4
10/2/2014 7:54:49 PM

Accepted Answer

MyStrings is a small table

Load filtered MyStrings in memory, then join with MyStaticStringTranslations using LINQ:

// Read the small table into memory, and make a dictionary from it.
// The last step will use this dictionary for joining.
var byId = db1.MyStrings
    .Where(x => homeStrings.Contains(x.Content))
    .ToDictionary(s => s.Id);
// Extract the keys. We will need them to filter the big table
var ids = byId.Keys.ToList();
// Bring in only the relevant records
var myStrings = db2.MyStaticStringTranslations
    .Where(y => ids.Contains(y.id))
    .AsEnumerable() // Make sure the joining is done in memory
    .Select(y => new {
        Id = y.id
        // Use y.id to look up the content from the dictionary
    ,   Original = byId[y.id].Content
    ,   Translation = y.translation
    });
6
10/2/2014 8:31:28 PM

Popular Answer

You are right that db1 and db2 can't be used in the same Linq expression. x and y have to be joined in this process and not by a Linq provider. Try this:

var x = db1.MyStrings.Where(xx => homeStrings.Contains(xx.Content)).ToEnumerable();

var y = db2.MyStaticStringTranslations.ToEnumerable();

var myStrings = (from a in x
                 join b in y on x.Id equals y.id
                    select new MyStringModel()
                    {
                        Id = x.Id,
                        Original = x.Content,
                        Translation = y.translation
                    }).ToList();

Refer to this answer for more details: The specified LINQ expression contains references to queries that are associated with different contexts

dasblinkenlight's answer has a better overall approach than this. In this answer I'm trying to minimize the diff against your original code.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow