Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 703
petko_stankoski Avatar asked Feb 11 '23 21:02

petko_stankoski


1 Answers

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
    });
like image 72
Sergey Kalinichenko Avatar answered Feb 15 '23 10:02

Sergey Kalinichenko