2012-07-17 18 views
4

实体框架存在问题。例如,如果我们这样做:一次性错误中断实体框架的后续使用

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); 

,然后我们尝试删除已映射的谁依赖于它的子实体的实体,这是合乎逻辑的,我们得到了一个错误。 (当数据库中存在依赖它的子项时,不能删除父项)。

之后,使用新的上下文实例,执行'ParentEntity.ChildEntities.ToList()'仍然存在问题!

解决方法是重新启动应用程序池,问题消失。

我们正在使用Autofac,并且上下文的生命周期被设置(并确认)为每个HttpRequest,因此该错误在其他地方仍然存在。任何想法可以做什么,以避免这些错误?

我们的猜测是objectcontext在其他地方是持久的,它将子实体的状态存储为“EntityState.Deleted”,所以这与在随后的调用中从数据库接收的实际数据冲突。

更新:好像仔细检查堆栈显示,有一个懒惰的内部背景:

[DbUpdateException: An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.] 
    System.Data.Entity.Internal.InternalContext.SaveChanges() +200 
    System.Data.Entity.Internal.LazyInternalContext.SaveChanges() +33 
    System.Data.Entity.DbContext.SaveChanges() +20 

也许如果我以某种方式禁用LazyInternalContext?这可以做到吗?

+0

不“*然后... * “的意思是:在一个新的请求(=新的上下文实例)? – Slauma 2012-07-17 14:55:24

+0

是的,新的上下文实例 – 2012-07-17 15:01:37

+0

这意味着,在新的上下文实例中加载父代和子代,然后再次删除父代并得到相同的错误,对吧?如果是这样,如果您不同时删除这些子级,并且关联级联删除处于禁用状态,则该错误并不令人意外。 – Slauma 2012-07-17 15:15:46

回答

0

如果你不想要得到的异常,并通过你的自我由于某种原因使数据库处于有效状态,您可以通过停止验证这样做的:

context.Configuration.ValidateOnSaveEnabled = false; // you can put this in the constructor of your context; 
context.SaveChanges();