Entity Framework 6 and Asp.Net Identity UserManager: Multiple DbContext

后端 未结 1 1384
野性不改
野性不改 2020-12-15 14:00

This is MVC 5/ EF6. So I have the following classes:

public class User : IdentityUser
{
    public User()
    {
        Levels = new List();
            


        
相关标签:
1条回答
  • 2020-12-15 14:38

    If you're using UserManager the way 'it came out of the box' then it's probably instantiated like this:

    public AccountController()
    : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new MyDbContext())))
    {
    }
    
    public AccountController(UserManager<ApplicationUser> userManager)
    {
        UserManager = userManager;
    }
    
    public UserManager<ApplicationUser> UserManager { get; private set; }
    

    It means that if you don't provide a UserManager instance to the AccountController constructor (and it's probably the case here), a new MyDbContext is created for the UserManager store.

    Yet, you have another instance of MyDbContext, as i can infer from this line in your code:

    Level level = DBContext.Levels.Where(s => s.Name == model.Level.Name).SingleOrDefault();
    

    All it means is that you have to make your UserManager use the same context:

    public AccountController() : this(null)
    {
    }
    
    public AccountController(UserManager<User> userManager = null)
    {
        DBContext = new MyDBContext();
    
        if (userManager == null)
            userManager = new UserManager<User>(new UserStore<User>(DBContext));
    
        UserManager = userManager;
    }
    
    public UserManager<User> UserManager { get; private set; }
    public MyDBContext DBContext;
    

    This way, you're creating the (only) MyDbContext instance first, then passing it to the UserManager constructor (as the IUserStore<User>).

    Also, you can definitely make a good use of Dependency Injection here and have the MyDbContext instance injected for you by a DI container and keeping your current code almost unchanged:

    public AccountController(MyDBContext context)
    : this(new UserManager<User>(new UserStore<User>(context)))
    {
        this.DBContext = context;
    }
    

    See Tutorial (for Microsoft Unity).

    0 讨论(0)
提交回复
热议问题