During the whole day I just tried to add a single property to my AspNetUsers table generated by identity. I wanted that property to be a foreign key to a "Clients" table so that each client has it's own user and all the data of the client is in that respective clients table.
So here is what I've done:
In the IdentityModels:
public class ApplicationUser : IdentityUser
{
[ForeignKey("Client")]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ClientID { get; set; }
public virtual Client Client { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
}
And in the AccountController
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var currentClient = new Client { Email = model.Email, Name = model.Name, Surname = model.Surname, PhoneNumber = model.PhoneNumber };
var context = new TNEAContext();
context.Clients.Add(currentClient);
context.SaveChanges();
var user = new ApplicationUser { UserName = model.Email, Email = model.Email, ClientID = currentClient.ClientID };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
return View(model);
}
And some other minor changes in the accountViewModel and the register view (in order to get those params).
I know that my problem is on the UserManager.CreateAsync method, but I don't know how to modify it, or what do I need to do in order to do that little change that is driving me mad :(