pet*_*ski 4 c# linq entity-framework
这是我的代码:
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();
Run Code Online (Sandbox Code Playgroud)
我得到的错误是指定的LINQ表达式包含对与不同上下文关联的查询的引用.我知道问题是我尝试从db1和db2访问表,但我该如何解决这个问题呢?
MyStrings是一张小桌子
MyStrings在内存中加载过滤,然后MyStaticStringTranslations使用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
});
Run Code Online (Sandbox Code Playgroud)