ASP.NET Identity 2 在保存扩展应用程序用户时插入重复数据或保存两次

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

我像这样向 ApplicationUser 添加了一些字段:

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

    public string FirstName { get; set; }

    public string CompanyName { get; set; } 
}

通过此代码注册用户时,它会自动插入重复数据 - type(在 UserType table 中)。看这段代码:

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)
        {
           ...
        }
     }

请帮我解决这个问题,当我调用 manager.Create() 时会发生什么,为什么它会向数据库插入类型?

您应该借助 GetOwinContext 获取 Type 对象。以下代码应该可以解决您的问题:

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