0

我在用户注册操作中有以下代码:

 var userStore = new UserStore<ApplicationUser>(db);
 var userManager = new UserManager<ApplicationUser>(userStore);

 var user = new ApplicationUser() { UserName = model.email, Email = model.email };

 IdentityResult result = await UserManager.CreateAsync(user, model.password);
 userManager.AddToRole(user.Id, "ARole");

AssociatedItem associatedItem = new AssociatedItem ();
associatedItem.email = model.email;

associatedItem.fullName = model.name;
associatedItem.account = user;
db.AssociatedItems.Add(associatedItem );
db.Entry(associatedItem ).State = EntityState.Modified;
db.SaveChanges();

这样做的问题是用户尝试再次创建,db.SaveChanges();这导致尝试使用重复的主键值的用户,这是不允许的。在创建用户之前,我无法将用户与 相关联associatedItem。我努力了:

db.Entry(user).State = EntityState.Unchanged;

之前db.SaveChanges();,但重复的主键问题仍然返回。有没有一种简单的方法可以在用户注册时将模型类与用户关联起来?

4

0 回答 0