Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 5 UserManager: The entity type ApplicationUser is not part of the model for the current context

I'm trying (but failing) to implement the MVC UserManager to my website. I thought my case is fairly trivial. I have a User class (Entity Framework - Database first) which contains all the user's info. Not every user from the User has access to the website. So in my ApplicationUser there is a link to this class. In code it looks like this:

public partial class User
{
    public int Id { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string Email { get; set; }
}

public class ApplicationUser : IdentityUser
{
    public virtual Entities.User UserInfo { get; set; }

    public ApplicationUser()
    {
        UserInfo = new Entities.User();
    }
}

When invoking the CreateUserAsync-method in the controller, it all goes wrong. Below you can find my controller code.

public class AccountController : BaseController
{
    public UserManager<ApplicationUser> UserManager { get; private set; }

    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var dbUser = new User 
            { 
                Firstname = model.FirstName, 
                Lastname = model.LastName, 
                Email = model.UserName 
            };
            db.Users.Add(dbUser);
            db.SaveChanges();

            var appUser = new ApplicationUser(model.UserName);
            appUser.UserInfo = dbUser;

            try
            {
                var result = await UserManager.CreateAsync(appUser, model.Password);
            }
            catch (Exception e)
            {
                db.Users.Remove(dbUser);
                db.SaveChanges();
            }
        }
    }
}

The CreateUserAsync-method gives the following error: The entity type ApplicationUser is not part of the model for the current context.

Now my questions:

  1. Am I doing this the 'mvc'-way? I feel this is a lot of work for something that in my opinion is trivial.
  2. If not, is there a better way to achieve this?
like image 208
Thijs Avatar asked Oct 21 '22 04:10

Thijs


1 Answers

The problem is that you're trying to add a User you added to one DbContext to a ApplicationUser you add to a different DbContext (created by the UserManager).

Instead, you should do this as a single operation. Just do this:

var dbUser = new User 
{ 
    Firstname = model.FirstName, 
    Lastname = model.LastName, 
    Email = model.UserName 
};
var appUser = new ApplicationUser(model.UserName);
appUser.UserInfo = dbUser;
try
{
   var result = await UserManager.CreateAsync(appUser, model.Password);
}
catch (Exception e)
{
   // show error or whatever
}
like image 105
Erik Funkenbusch Avatar answered Oct 27 '22 00:10

Erik Funkenbusch