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:
- Am I doing this the 'mvc'-way? I feel this is a lot of work for something that in my opinion is trivial.
- If not, is there a better way to achieve this?
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: