一个上下文引用LINQ查询引发多个引用异常-错误? [英] One context reference LINQ query throws multiple references exception - BUG?

查看:69
本文介绍了一个上下文引用LINQ查询引发多个引用异常-错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码:

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

其中adminGroupUserIDsIQueryable<GUID>,它是从查询到MainEntities的不同实例形成的.

where adminGroupUserIDs is an IQueryable<GUID> that is formed from a query to a different instance of MainEntities.

LINQ在此查询中抱怨:

With this query LINQ complains that:

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

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

有什么想法吗?

推荐答案

我无法从您在此处显示的代码中确定,但是我很确定adminGroupUserIDs是另一个未进行查询的结果已被检索,并使用MainEntities的其他实例创建.您不能混合来自不同上下文的查询,甚至不能混合来自同一上下文类的不同实例.尝试将其更改为以下内容:

I can't be certain from the code you show here, but I'm pretty sure that adminGroupUserIDs is the result of another query that hasn't been retrieved yet, and was created with a different instance of MainEntities. You can't mix queries from different contexts, not even different instances of the same context class. Try changing it to the following:

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

这篇关于一个上下文引用LINQ查询引发多个引用异常-错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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