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?
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.
Dispose() method of a class implementing
IDisposable means you're telling the library "I am done with this object. I will no longer use it. You may clear up as needed." This is not specific to Entity Framework.
For most classes, attempts to continue using the object after calling
Dispose() will fail, sometimes with an explicit exception alerting you to the problem, sometimes by an internal exception caused by corrupted object state. You should not assume Entity Framework is an exception to that: after calling
dbContext.Dispose(), you should no longer use the context referenced by
However, there's nothing stopping you from creating a new context immediately afterwards:
dbContext.Dispose(); dbContext = new DbContext();
This new context will have absolutely no recollection of any unsaved changes you made in the old context. There are plenty of good cases in which this approach is the most practical.