简体   繁体   中英

Linq queries references different contexts but actually it is not

I am trying to get data from two different tables using EF 6, it is a asp.net mvc 5 project with Identity 2.0 used in it, however when i join two tables, i am getting the error that contexts of both entities are different, however it is not, here is my code:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public DbSet<UserAccountStatus> UserAccountStatuss { get; set;}

    public static ApplicationDbContext Create()
    {
       return new ApplicationDbContext();
    }
}

and here is my linq query :

var result = (from user in DbContext.Users
              join accountStatus in DbContext.UserAccountStatuss on user.Id equals accountStatus.UserId
              where user.Email == email
              select accountStatus.AccountEnabled).FirstOrDefault();

My DbContext property:

public ApplicationDbContext DbContext
{
    get
    {
        return _dbContext ?? ApplicationDbContext.Create();
    }
    private set
    {
        _dbContext = value;
    }

}

Exact error is :

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

and this is not a duplicate, i have seen other questions, in those user are actually trying different contexts, but in my case i have one.

your lazy instantiaiton is the problem. It should be

private ApplicationDbContext _dbContext;
public ApplicationDbContext DbContext
{
    get
    {
        if(_dbContext==null){_dbContext=ApplicationDbContext.Create();}
        return _dbContext;
    }


}

Edit: Example with Lazy

private Lazy<ApplicationDbContext> _dbContext=new Lazy<ApplicationDbContext>(()=>ApplicationDbContext.Create());
public ApplicationDbContext DbContext
{
    get
    {
        return _dbContext.Value;
    }


}
public ApplicationDbContext DbContext
{
    get
    {
        return _dbContext ?? ApplicationDbContext.Create();
    }
    private set
    {
        _dbContext = value;
    }

}

You get a new context every time...

public ApplicationDbContext DbContext
{
    get
    {
        if(_dbContext == null)
            _dbContext = ApplicationDbContext.Create();
        return _dbContext;
    }    
}

Try this

Your property will return a new context each time it is accessed. You need to store the newly created context so it can be returned the next time it is used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM