指定的LINQ表达式包含对与C#中的不同上下文错误相关联的查询的引用 [英] The specified LINQ expression contains references to queries that are associated with different contexts error in c#

查看:75
本文介绍了指定的LINQ表达式包含对与C#中的不同上下文错误相关联的查询的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要执行此查询:

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函数具有以下结构:

as you can see i create a join between 4 tables and the get function has this structure :

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

但是我得到这个错误:

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

The specified LINQ expression contains references to queries that are associated with different contexts.

推荐答案

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

You can't combine in one query data retrieved from multiple contexts, these multiple contexts may point to two difference databases or have different options, then the query might not execute.

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

It seems that each repository creates its own DataContext object and retrieves the data using that object.

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

To solve that without have to pass the context and share it between all repositories, you might want to return a List from the Get() method and not an IQueryable. I don't know if you think that Get() is executing the query but it is not. It is just storing information about the query in IQueryable. Only when you call .ToList(); inside your ShowSheet method, the queries of Get() gets executed.

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

Else, you need to create one context and use it in all the repositories in this query. Your option here is to have the constructor of the repository (or the Get() Method itself) accept a YourContext parameter. Then you pass the context : _sheetRepository.Get(context) so that all of them share the same object.

这篇关于指定的LINQ表达式包含对与C#中的不同上下文错误相关联的查询的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆