Search code examples
c#asp.netwebformsasp.net-identity-2

ASP.NET Identity 2 when saving extended Application User it inserts duplicate data or saving two times


I added some fields to ApplicationUser like this:

 public class ApplicationUser : IdentityUser
{
    public virtual UserType Type { get; set; }

    public string FirstName { get; set; }

    public string CompanyName { get; set; } 
}

When registering user by this code, it automatically inserts duplicate data - type (in UserType table). Look at this code:

protected void CreateUser_Click(object sender, EventArgs e)
    {
        var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
        Guid typeID = Guid.Parse(drpType.SelectedValue);
        var type = db.UserTypes.First(t => t.ID == typeID);
        var user = new ApplicationUser() { UserName = Email.Text, Email = Email.Text, FirstName = FirstName.Text, CompanyName = CompanyName.Text, Contacts = Contacts.Text, Type = type };
        type=null;
        IdentityResult result = manager.Create(user, Password.Text);
        if (result.Succeeded)
        {
           ...
        }
     }

Please help me with this issue, what happen when i call manager.Create() why it inserts type to database?


Solution

  • You should get the Type object with the help of GetOwinContext. The following code should fix your problem:

    var dbcontext= Context.GetOwinContext().Get<ApplicaitionDbContext>();
    var type = dbcontext.UserTypes.First(t => t.ID.Equals(typeID));