Search code examples
.netentity-frameworkentity-framework-6dbcontextrollback

What if I call DbContext.Dispose without calling DbContext.SaveChanges?


I am looking for a way to roll back entity changes. I came across this answer which shows how to set entity state, but I am wondering what happens if I simply dispose of my dbContext instance without calling dbContext.SaveChanges() or manipulating the entity states.

The code I wrote to do so definitely works, but am I leaving anything in an unstable state by rejecting changes in this way?


Solution

  • what happens if I simply dispose of my dbContext instance without calling dbContext.SaveChanges() or manipulating the entity states

    Nothing. The instances that were previously attached to the now disposed DbContext instance continue to exist as any normal instances would assuming there is a handle on those instances somewhere by something. If there is not the memory will be release and eventually garbage collected as any other normal instance of something would if there is no handle to it. The state of the entities in memory stays as is, nothing in memory is automatically reverted back. The database store also stays "as is" meaning there is no call from the DbContext to the datastore.

    am I leaving anything in an unstable state by rejecting changes in this way

    No, at least not in the data store. In memory it is hard to say, it depends on where the code left off and what the dependencies were on the modifications up until that point. Lets assume its a stateless asp.net application, maybe the request simply ends and in this case nothing unstable should happen with any of the following requests as they should retrieve anything needed back from the data store.

    If its something more long lived like a windows app then you might have to manually make sure that any pointers/handles to instances that were previously being tracked are either updated with the now reverted in-memory state or release those pointers.

    As far as any new DbContext instances are concerned they all operate independent of each other so there is no continuation between them. The new DbContext does not know about state being tracked or state that had been tracked by any other DbContext instance.