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