One context reference LINQ query throws multiple references exception - BUG?

c#, linq

Solution

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

Problem

I'm using the following code: ``` 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(); } ``` where `adminGroupUserIDs` is an `IQueryable<GUID>` that is formed from a query to a different instance of `MainEntities`. With this query LINQ complains that: The specified LINQ expression contains references to queries that are associated with different contexts. Any ideas why?

Original source

Related problems