我将用户详细信息分成了自己的表配置文件,并带有ApplicationUser的外键,但现在我的插入失败。
所以我得到了以下表格:
AspNetUsers
{
Id
UserName
PasswordHash
SecurityStamp
Descriminator
}
和
Profiles
{
Id
FirstName
LastName
Email
AspNetUser_Id
}
所以我通过添加如下额外字段来更改 RegisterViewModel :
public class RegisterViewModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[Display(Name = "First name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last name")]
public string LastName { get; set; }
[Required]
public string EMail { get; set; }
}
...并将“个人档案”表中的字段合并到 Register.cshtml 中,我想将模型中的信息存储到两个表中。所以我的AccountController.Register看起来像这样:
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.UserName };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var profile = new Profile
{
FirstName = model.FirstName,
LastName = model.LastName,
EMail = model.EMail,
User = user
};
var db = new DecoupleDb();
db.Profiles.Add(profile);
db.SaveChanges();
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
但现在我一直在
上收到错误db.SaveChanges();
错误说我试图违反AspNetUsers表的主键
&#34;违反PRIMARY KEY约束&#39; PK_dbo.AspNetUsers&#39;。无法在对象&#39; dbo.AspNetUsers&#39;中插入重复键。重复键值为(372775e0-bad5-452f-b65c-cd9bf7b80b34)。 该声明已被终止。&#34;
我无法理解为什么,因为它只是一个外键,因此当我添加配置文件时,不应该创建AspNetUser,或者我认为。
有人看到修复?
答案 0 :(得分:0)
我找到了答案。我必须存储新用户,然后将其取回并填充配置文件。 像这样:
if (ModelState.IsValid)
{
var user = new ApplicationUser {UserName = model.UserName};
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var newUser = db.ApplicationUsers.Find(user.Id);
var profile = new Profile
{
FirstName = model.FirstName,
LastName = model.LastName,
Email = model.Email,
Identity = newUser,
};
db.Profiles.Add(profile);
db.SaveChanges();
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}