Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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?

like image 895
seebiscuit Avatar asked Jun 20 '26 23:06

seebiscuit


1 Answers

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(); 
}
like image 136
Allon Guralnek Avatar answered Jun 23 '26 17:06

Allon Guralnek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!