在有關此錯誤的各種上下文中有許多問題,到目前爲止,我一直無法找到適用於我的情況的問題。INSERT語句與EF核心中的FOREIGN KEY約束衝突
我有一個多對多的關係,我試圖建立一個第三表。這基本上是經理協會的一個人。所有管理者都是人,但並不是所有人都是管理者,而且每個人都有很多管理者,每個管理者都有很多人。所以在經理的桌子上是PersonIds。在編輯中的人員控制器是將人員與經理關聯的選項。當點擊可用管理者和點擊保存,我得到的錯誤:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.ManagerToEngineer_dbo.Manager_ManagerId". The conflict occurred in database "PROJECTNAME_16ce3f6a2a6c4ff0b1ce147d126984ba", table "dbo.Manager", column 'ManagerId'. The statement has been terminated.
SaveChanges方法導致這個錯誤:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(PersonViewModel person)
{
if (ModelState.IsValid)
{
//var MyPerson = db.people.Find(person.PersonId);
//MyPerson.FirstName = person.FirstName;
//MyPerson.LastName = person.LastName;
foreach (var item in db.ManagersToEngineers)
{
if (item.EngineerId == person.PersonId)
{
db.Entry(item).State = EntityState.Deleted;
}
}
foreach (var item in person.EngineerManagers)
{
if (item.Checked)
{
db.ManagersToEngineers.Add(new ManagerToEngineer() { EngineerId = person.PersonId, ManagerId = item.Id });
}
}
//db.Entry(person).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(person);
}
相關機型:
public class ManagerToEngineer
{
[Key]
public int ManagerToEngineerId { get; set; }
[Required]
[ForeignKey("engineer")]
public int EngineerId { get; set; }
[Required]
[ForeignKey("manager")]
public int ManagerId { get; set; }
public virtual Person engineer { get; set; }
public virtual Manager manager { get; set; }
}
public class Manager
{
[Key]
public int ManagerId { get; set; }
[Required]
[ForeignKey("person")]
public int EngineerId { get; set; }
public virtual Person person { get; set; }
public ICollection<ManagerToEngineer> ManagersToEngineers { get; set; }
}
public class PersonViewModel
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[Display(Name = "Managers")]
public List<CheckBoxViewModel> EngineerManagers { get; set; }
}
public class CheckBoxViewModel
{
public int Id { get; set; }
public string FullName { get; set; }
public bool Checked { get; set; }
}
您應該查看以下有關EF Core中的多對多關係的文檔:https://docs.efproject.net/en/latest/modeling/relationships.html#many-to-many。 –