这是我的代码:
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();
而且我收到错误消息,指出指定的 LINQ 表达式包含对与不同上下文关联的查询的引用。我知道问题在于我尝试从 db1 和 db2 访问表,但我该如何解决这个问题?
最佳答案
MyStrings
is a small table
在内存中加载过滤后的 MyStrings
,然后使用 LINQ 加入 MyStaticStringTranslations
:
// 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
});
关于c# - LINQ 表达式包含对与不同上下文关联的查询的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26168587/