实体框架和自引用表AND自引用实体

时间:2013-02-21 14:36:23

标签: c# entity-framework linq-to-entities

我有一个自引用表,有时会有一个自引用实体,如下所示: (是的,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 个答案:

答案 0 :(得分:1)

这里的问题是,这需要对数据库进行两次写入以保存单个实体(一个用于获取存储生成的PK,另一个用于将该PK保存到FK中)或者需要更新管道和提供者模型的能力生成更复杂的SQL,可以在服务器上完成所有这些操作。目前,更新管道不支持这两种方式。

正如您所说,解决方法是手动执行双重保存。

我认为我们没有跟踪此特定问题的错误,因此我建议您在CodePlex上提交一个错误。您可能还会考虑提供修复程序 - 我不确定修复程序有多难,因为我不太熟悉更新管道代码。

相关问题