簡體   English   中英

實體框架和自引用表以及自引用實體

[英]Entity Framework and self referencing table AND self referencing Entity

我有一個自引用表,有時它具有一個自引用實體,例如:( 是的,IdFamily是可為空的)

...
//At my Business
newFile.Family = newFile;
...
//At my ASP.NET MVC action I call:
context.SaveChanges();

它拋出一個DbUpdateException:

[UpdateException: Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.]
   System.Data.Mapping.Update.Internal.UpdateTranslator.DependencyOrderingError(IEnumerable`1 remainder) +4302030
   System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) +4300384
   System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options) +583
   System.Data.Entity.Internal.InternalContext.SaveChanges() +382

[DbUpdateException: Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.]
   System.Data.Entity.Internal.InternalContext.SaveChanges() +485
   System.Data.Entity.Internal.LazyInternalContext.SaveChanges() +63
   System.Data.Entity.DbContext.SaveChanges() +75

解決方法很丑陋,因為我需要調用SaveChanges,設置Id並再次調用SaveChanges。 打破UnitOfWork,因此要變通解決,我需要將我的所有請求都放入TransactionScope中。

...
//At my Business
//newFile.Family = newFile;
context.SaveChanges();//BREAK UNIT OF WORK
newFile.IdFamily = newFile.Id;
...
//At my ASP.NET MVC action I call(Action Wrapped in TransactionScope):
context.SaveChanges();

這里的問題是,這需要兩次寫入數據庫以保存單個實體(一次以獲取商店生成的PK,另一次將該PK保存到FK中)或更新管道和提供程序模型能夠生成更多實體的能力。復雜的SQL,可以在服務器上完成所有這些操作。 當前,更新管道不支持其中任何一種。

如您所說,解決方法是手動執行雙重保存。

我認為我們沒有跟蹤此特定問題的錯誤,因此建議您在CodePlex上提交一個。 您可能還考慮提供一個修復程序-我不確定該修復程序有多困難,因為我並不熟悉更新管道代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM