您好,我遇到了这个错误
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.AspNetUsers_dbo.Contacts_ContactID".
The conflict occurred in database "aspnet-COGMakati-20140119015553", table "dbo.Contacts", column 'ContactID'.
The statement has been terminated.
我正在使用 Entity Framework 和 MVC 5 的 IdentityUser,所以我真的迷失了自己在做什么:|
这就是我要填充的内容:
public class User : IdentityUser
{
[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; }
public string Birthday { get; set; }
[Display(Name = "Referred By")]
public string LifegroupPreference { get; set; }
[Display(Name = "Civil Status")]
public string CivilStatus { get; set; }
public int EducationID { get; set; }
public int WorkID { get; set; }
public int ContactID { get; set; }
public int FamilyID { get; set; }
public int SpiritualID { get; set; }
public int GrowthMilestoneID { get; set; }
[ForeignKey("EducationID")]
public virtual Education Education { get; set; }
[ForeignKey("WorkID")]
public virtual Work Work { get; set; }
[ForeignKey("ContactID")]
public virtual Contact Contact { get; set; }
[ForeignKey("FamilyID")]
public virtual Family Family { get; set; }
[ForeignKey("SpiritualID")]
public virtual Spiritual Spiritual { get; set; }
[ForeignKey("GrowthMilestoneID")]
public virtual GrowthMilestone GrowthMilestone { get; set; }
}
在我看来,Contact
甚至在创建 User 之前就已创建。我不知道为什么会这样,因为当不使用 IdentityUser
时,这段代码会很好地填充它。
现在这是 Register
方法:
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = model.GetUser();
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var idManager = new IdentityManager();
idManager.AddUserToRole(user.Id, "User");
await SignInAsync(user, isPersistent: false);
return RedirectToAction("ViewAllMembers", "Home");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
最佳答案
您可能正在尝试使用不存在的外键访问或插入。转到您的 dbo.Contacts
表并查找具有该键的记录。您会在表中找不到包含该键的记录。您需要使用该 key 创建记录或使用另一个(现有) key 。
关于c# - INSERT 语句与 FOREIGN KEY 约束错误冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21518995/