(我已檢查相關問題,但無法找到答案。)一次保存相關實體 - 保存不會爲其關係公開外鍵屬性的實體時發生錯誤
我是用Code First Entity Framework 6做一些測試。 我有一個引用兩個「Parent」實體的「Child」實體。
我想創建子實體和父實體,然後將它們一次全部保存(這樣我就可以減少db.Save()調用的次數,並將其保留爲一個工作單元)。
public class Child
{
public int ChildID { get; set; }
public string Name { get; set; }
public virtual Parent Father { get; set; }
public virtual Parent Mother { get; set; }
}
public class Parent
{
public int ParentID { get; set; }
public string Name { get; set; }
[ForeignKey("Child")]
public int? ChildID { get; set; }
public virtual Child Child { get; set; }
}
(混亂設置的位 - 父母實際上是在關係孩子的「孩子們」我知道這是不好的抽象這只是一個測試。)
控制器:
public ActionResult AddWithParents()
{
Parent father = new Parent { Name = "Test Father" };
Parent mother = new Parent { Name = "Test Mother" };
Child newChild = new Child
{
Name = "Test Child",
Father = father,
Mother = mother
};
db.Children.Add(newChild);
father.Child = newChild;
mother.Child = newChild;
db.SaveChanges();
return RedirectToAction("Index");
}
這可以工作,但不會填充Parent.ChildID外鍵。
如果我這樣做father.Child = newChild對象,我得到以下錯誤:
An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details. Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
有沒有什麼辦法讓這個工作?
什麼是你的內部異常?如果它顯示'SqlException',請檢查您的日期時間數據類型是否存在空值或超範圍值。 –
模型中沒有數據時間。 有人重新格式化了我的問題,所以內部異常是主要異常的一部分,但內部異常是: 無法確定依賴操作的有效順序。由於外鍵約束,模型要求或商店生成的值,可能會存在依存關係。 – mcfroob
那麼,你的內部異常告訴我你有循環依賴問題,EF試圖找到一個具有null或無效主鍵值的實體。檢查外鍵是否具有可空類型或檢查相關表之間的關係。那麼,你想要做什麼類型的關係(1:1,1:n)? –