简体   繁体   中英

Entity Framework and self referencing table AND self referencing Entity

I have a self-reference table that sometimes has a self-reference entity, like this: (Yes, IdFamily is nullable)

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

It throws a 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

The workaround is ugly, because I need to call SaveChanges, set the Id and call SaveChanges again. Breaking the UnitOfWork, so to workaround the workaround I need to put all my Request inside a 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();

The problem here is that this requires either two writes to the database to save a single entity (one to get the store-generated PK, another to save that PK into the FK) or the ability for the update pipeline and provider model to generate more complex SQL that can do this all on the server. Currently the update pipeline doesn't support either of those things.

The workaround is, as you say, to perform the double save manually.

I don't think we have a bug tracking this specific issue, so I would suggest that you file one on CodePlex. You might also consider contributing a fix--I'm not sure how difficult the fix would be since I'm not super-familiar with the update pipeline code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM