【问题标题】:The specified LINQ expression contains references to queries that are associated with different contexts error in c#指定的 LINQ 表达式包含对与 c# 中的不同上下文错误关联的查询的引用
【发布时间】:2016-12-02 07:22:07
【问题描述】:

我想执行这个查询:

public List<ViewSheet> ShowSheet(List<Sheet> lst)
{
   var res = (from sheet in _sheetRepository.Get()
       join line in _lineRepository.Get() on sheet.LineId equals line.Id
       join basemat in _baseMaterialRepository.Get() on sheet.BaseMaterialId equals basemat.Id
       join lineend in _lineEndRepository.Get() on sheet.LineEndId equals lineend.Id
       join Paint in _paintCodeRepository.Get() on sheet.PaintCodeId equals Paint.Id 
       select new ViewSheet()
       {
           BaseMaterialId = basemat.Name,
           Catagory = sheet.Catagory,

           LineEndId = lineend.Name,
           LineId = line.LineNumber,
           MtPercent = sheet.MtPercent,
           PAndId = sheet.PAndId,
           PaintCodeId = Paint.Name,
           ParentId = sheet.ParentId,

       }).ToList();
   return res;
}

如您所见,我在 4 个表之间创建了一个连接,get 函数具有以下结构:

public interface ISheetRepository
{
    IQueryable<Sheet> Get();
    bool Save();       
}

但我收到此错误:

指定的 LINQ 表达式包含对以下查询的引用 与不同的上下文相关联。

【问题讨论】:

    标签: c# entity-framework linq join


    【解决方案1】:

    您不能将从多个上下文中检索到的数据组合在一个查询中,这些多个上下文可能指向两个不同的数据库或具有不同的选项,那么查询可能不会执行。

    似乎每个存储库都创建了自己的DataContext 对象并使用该对象检索数据。

    要解决这个问题而不必传递上下文并在所有存储库之间共享它,您可能希望从Get() 方法返回一个列表,而不是IQueryable。我不知道您是否认为Get() 正在执行查询,但事实并非如此。它只是在IQueryable 中存储有关查询的信息。只有当你在 ShowSheet 方法中调用 .ToList(); 时,Get() 的查询才会被执行。

    否则,您需要创建一个上下文并在此查询的所有存储库中使用它。您在这里的选择是让存储库的构造函数(或Get() 方法本身)接受YourContext 参数。然后传递上下文:_sheetRepository.Get(context),这样它们都共享同一个对象。

    【讨论】:

      猜你喜欢
      • 2011-11-12
      • 2021-11-12
      • 2011-07-30
      • 1970-01-01
      • 2018-05-09
      • 2011-10-24
      相关资源
      最近更新 更多