[英]{“The INSERT statement conflicted with the FOREIGN KEY constraint The statement has been terminated.”}
there is also a userstats table, I want a one to one relationship, but i'm getting the above error when I try and register a user.Thanks for the help! 还有一个userstats表,我想要一对一的关系,但我在尝试注册用户时遇到上述错误。谢谢你的帮助!
User Table: 用户表:
public class User
{
[Key]
public int ID { get; set; }
public int UserStatsID { get; set; }
public virtual UserStats UserStats { get; set; }
}
Userstats Table Userstats表
[Key]
public int ID { get; set; }
public int UserID { get; set;}
[Required]
public User User { get; set; }
RegisterDetailsController RegisterDetailsController
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(User user)
{
if (ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
if (user.Gender == Gender.Male )
{
return RedirectToAction("RegisterMale", "RegisterStats", new {id = user.ID });
}
else
{
return RedirectToAction("RegisterFemale", "RegisterStats", new { id = user.ID });
}
}
return View(user);
}
You can't have a true 1:1 relationship enforced entirely through foreign keys, as the inserts have to be done one at a time and doing that would violate the constraint. 您不能完全通过外键强制执行真正的1:1关系,因为必须一次执行一次插入操作,这样做会违反约束。
Instead, you will have to make the relationship 1:0. 相反,你必须以1:0的比例建立关系。 Do this by making UserStatsID
an int?
通过使UserStatsID
成为一个int?
做到这一点int?
instead of an int
. 而不是一个int
。
The problem is that your table has a foreign key to the UserStats
table. 问题是您的表具有UserStats
表的外键。 If the foreign key
field is nullable
then you can use int?
如果foreign key
字段可以为nullable
那么你可以使用int?
and put a null there if no value is provided. 如果没有提供值,则在那里放一个null。 Anyway, the problem is that you are trying to insert a record where the foreign key's value does not exist as a primary key in the referenced table. 无论如何,问题是您正在尝试插入一个记录,其中外键的值不存在作为引用表中的主键。 Make sure that whenever you assign a value to a foreign key, the referenced table has that key in a record. 确保无论何时为外键指定值,引用的表都会在记录中包含该键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.