2013-02-21 74 views
1

我有,有時有自我參照實體自我引用的表,如下所示: (是的,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(); 

回答

1

這裏的問題是,這需要兩根寫入到數據庫來保存單個實體(一個拿到店裏生成PK,另一個保存PK到FK)或更新的能力管道和提供者模型來生成更復雜的SQL,這些都可以在服務器上完成。目前,更新管道不支持這兩種情況。

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

我不認爲我們有跟蹤這個特定問題的錯誤,所以我建議您在CodePlex上提交一個。您也可以考慮提供修補程序 - 我不確定修復程序有多困難,因爲我不熟悉更新管道代碼。

+0

很遺憾聽到它,但感謝澄清。我無法找到任何有關它的信息,只是自引用不同的實體表。我很樂意爲EF做出貢獻,我也計劃實施DbContext.IsDirty,我只是不知道我是否具備這些技能,EF代碼庫是巨大的。 – 2013-02-25 18:42:31