一个上下文引用LINQ查询抛出多个引用异常-BUG

本文关键字:引用 异常 -BUG 查询 LINQ 一个 上下文 | 更新日期: 2023-09-27 18:27:33

我使用以下代码:

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(); 
}

其中CCD_ 1是从对CCD_ 3的不同实例的查询形成的CCD_。

通过此查询,LINQ抱怨道:

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

有什么想法吗?

一个上下文引用LINQ查询抛出多个引用异常-BUG

我不能从您在这里显示的代码中确定,但我很确定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(); 
}

尝试将.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(); 
}