我使用以下代码:
using(MainEntities mainContext = new MainEntities())
{
return (from member in mainContext.aspnet_Membership
where adminGroupUserIDs.Contains(member.UserId)
select new
{
FullName = member.FirstName + " " + member.LastName,
UserName = (from user in mainContext.aspnet_Users
where user.UserId == member.UserId
select user.UserName)
}).ToList();
}
其中adminGroupUserIDs
是IQueryable<GUID>
,是根据查询形成MainEntities
的其他实例。
有了这个查询,LINQ抱怨说:
指定的LINQ表达式包含对与不同上下文关联的查询的引用。
任何想法为什么?
答案 0 :(得分:4)
我无法从您在此处显示的代码中确定,但我非常确定adminGroupUserIDs
是另一个尚未检索到的查询的结果,并且是使用不同的实例创建的MainEntities
。您不能混合来自不同上下文的查询,甚至不能混合相同上下文类的不同实例。尝试将其更改为以下内容:
var loadedAdminGroupUserIDs = adminGroupUserID.ToArray();
using(MainEntities mainContext = new MainEntities())
{
return (from member in mainContext.aspnet_Membership
where loadedAdminGroupUserIDs.Contains(member.UserId)
select new
{
FullName = member.FirstName + " " + member.LastName,
UserName = (from user in mainContext.aspnet_Users
where user.UserId == member.UserId
select user.UserName)
}).ToList();
}
答案 1 :(得分:0)
尝试将.FirstOrDefault()
添加到子查询中。
using(MainEntities mainContext = new MainEntities())
{
return (from member in mainContext.aspnet_Membership
where adminGroupUserIDs.Contains(member.UserId)
select new
{
FullName = member.FirstName + " " + member.LastName,
UserName = (from user in mainContext.aspnet_Users
where user.UserId == member.UserId
select user.UserName).FirstOrDefault()
}).ToList();
}