简体   繁体   English

实体框架和自引用表以及自引用实体

[英]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) 我有一个自引用表,有时它具有一个自引用实体,例如:( 是的,IdFamily是可为空的)

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

It throws a DbUpdateException: 它抛出一个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. 解决方法很丑陋,因为我需要调用SaveChanges,设置Id并再次调用SaveChanges。 Breaking the UnitOfWork, so to workaround the workaround I need to put all my Request inside a TransactionScope. 打破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();

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. 这里的问题是,这需要两次写入数据库以保存单个实体(一次以获取商店生成的PK,另一次将该PK保存到FK中)或更新管道和提供程序模型能够生成更多实体的能力。复杂的SQL,可以在服务器上完成所有这些操作。 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. 我认为我们没有跟踪此特定问题的错误,因此建议您在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. 您可能还考虑提供一个修复程序-我不确定该修复程序有多困难,因为我并不熟悉更新管道代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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