为什么我仍然收到System.NotSupportedException

时间:2014-02-20 17:53:09

标签: c# .net linq entity-framework-6

我的代码是:

using( var ctxA = new AEntities())
using( var ctxB = new BEntities())
{
    var listOfA = (from A in AEntities.AEntity select A).ToList();
    var listOfB = (from B in BEntities.BEntity
                   where listOfA.Select( A = A.Id)contains(B.Id) 
                   select B).ToList();
}

我收到了错误:

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

然而,由于'ToList'我已经在AEntity中进行了一次提取,这只能查询其中一个上下文,不是吗?

如何将两个查询分开仍然使用一个列表来查询另一个?

2 个答案:

答案 0 :(得分:1)

尝试仅将IDs存储到listOfA

 var listOfA = (from A in AEntities.AEntity select A.Id).ToList();
 var listOfB = (from B in BEntities.BEntity
               where listOfA.Contains(B.Id) 
               select B).ToList();

答案 1 :(得分:0)

如果有人想知道,我的问题的答案是:

var listOfA = (from A in AEntities.AEntity select A.Id).ToList();
List<long> listOfIdsOfA = listOfA.Select( A=>A.id).ToList();
var listOfB = (from B in BEntities.BEntity
           where listOfIdsOfA.Contains(B.Id) 
           select B).ToList();

Selman回答的唯一区别是在第一次查询后创建Id的列表。这就是为什么我也需要整个实体。