A one time error breaks subsequent usage of Entity framework
We have a problem with entity framework. For example if we do:
and then we try to delete an entity that has mapped child entities who depend on it, it is logical that we get an error. (Cannot delete parent when there are children in database that depend on it).
Afterwards, using a new context instance, doing a 'ParentEntity.ChildEntities.ToList()' there is still a problem!
A workaround is to restart the app pool, and the problem goes away.
We are using Autofac and the lifecycle of the context is set (and confirmed) to per HttpRequest, so the error persists somewhere else. Any idea what can be done so as to avoid these errors?
Our guess is that the objectcontext is persistent somewhere else, and it stores the state of the child entities as "EntityState.Deleted" so this conflicts with the actual data received from the database on subsequent calls.
Update: Seems like a closer examination of the stack reveals that there is a lazy internal context:
[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
Maybe if I were to somehow disable LazyInternalContext? Can this be done?
If you don't want to get the exceptions and keep the database in a valid state by your self for some reason you can do so by stopping validation:
context.Configuration.ValidateOnSaveEnabled = false; // you can put this in the constructor of your context; context.SaveChanges();