LINQ表达式包含对与不同上下文相关联的查询的引用 [英] The LINQ expression contains references to queries that are associated with different contexts
本文介绍了LINQ表达式包含对与不同上下文相关联的查询的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我的代码:
VAR myStrings =(从X在db1.MyStrings.Where(X => homeStrings。载有(x.Content))
加入Ÿ在x.Id db2.MyStaticStringTranslations等于y.id
选择新MyStringModel()
{
n = x.Id,
原件= x.Content,
翻译= y.translation
})了ToList()。
和我得到指定的LINQ表达式包含到与不同的上下文相关的查询引用错误。我知道,问题是,我试图从两个DB1和DB2访问表,但我怎么解决这个问题?
解决方案
MyStrings
是一个小桌子
块引用>
加载过滤
MyStrings
在内存中,然后用MyStaticStringTranslations
加入使用LINQ://读取小表到内存中,并进行了字典如此。
//最后一步将使用该字典的加盟。
VAR byId = db1.MyStrings
。凡(X => homeStrings.Contains(x.Content))
.ToDictionary(S = GT; s.Id);
//提取密钥。我们需要他们来过滤大表
VAR IDS = byId.Keys.ToList();
//把只在相关的记录
VAR myStrings = db2.MyStaticStringTranslations
。凡(Y => ids.Contains(y.id))
.AsEnumerable() //确保在内存$ b $完成b。选择(Y =>加盟,新{
n = y.id
//使用y.id查找从字典内容
,原件= byId [y.id] .Content
,翻译= y.translation
});
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?
解决方案
MyStrings
is a small tableLoad filtered
MyStrings
in memory, then join withMyStaticStringTranslations
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 });
这篇关于LINQ表达式包含对与不同上下文相关联的查询的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文