[英]DbUpdateException on SaveChanges if child foreign key already exists - in Entity Framework Code First
[ 在實體框架5.0 RC中使用代碼優先DbContext ]
public class Compositon
{
public string Id { get; set; }
public string SimpletonId { get; set; }
[ForeignKey("SimpletonId")]
public Simpleton Simpleton { get; set; }
public string CompanitonId { get; set; }
[ForeignKey("CompanitonId")]
public Companiton Companiton { get; set; }
}
var composition = new Compositon();
compositon.Id = "UniquePrimaryKey";
var simpleton = new Simpleton();
// This foreign key does not exist in database yet
simpleton.Id = "Simpleton1";
composition.Simpleton = simpleton;
var companiton = new Companiton();
companiton.Id = "SomeOther1";
composition.Companiton = companiton;
// Repositor references the DbContext
Repositor.Compositons.Add(composition);
Repositor.SaveChanges();
var composition = new Compositon();
compositon.Id = "AnotherUniquePrimaryKey";
var simpleton = new Simpleton();
// This foreign key already exists in database
simpleton.Id = "Simpleton1";
composition.Simpleton = simpleton;
var companiton = new Companiton();
companiton.Id = "SomeOther2";
composition.Companiton = companiton;
Repositor.Compositons.Add(composition);
Repositor.SaveChanges();
DbUpdateException: An error occurred while updating the entries.
我需要能夠將這些父類保存到數據庫中,因為它們有時是唯一的,即使它們有時包含已存儲的導航屬性,又該如何保存父類呢?
在第二遍中,您將需要從DbContext
檢索現有的Simpleton
。 我猜你可以這樣做:
`simpleton = Repositor.Simpletons.First(s => s.Id == "Simpleton1");`
當前,您正在創建一個全新的實體,實體框架會嘗試將其插入,從而導致密鑰沖突。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.