c# - LINQ 表达式包含对与不同上下文关联的查询的引用

标签 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();

而且我收到错误消息,指出指定的 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/

相关文章:

c# - 安卓 JSON 安全

c# - 使用 EntityFramework.Core 从自引用表加载完整层次结构

c# - 如何从数据表中获取最高值?

wcf - 具有共享对象的 Entity Framework Attach() 对象树

c# - 动态构建从 linq 到实体查询的选择列表

c# - Entity Framework : adding to one-to-many relationship gives concurrency exception

c# - Unity偏移循环总是从头开始?

c# - 我正在尝试从 c# 中的 xml 文件读取目录并遇到问题

c# - 我可以不使用 break; 来使用 switch 语句吗?

c# - 使用自定义条件和分隔符拆分字符串