efcore: Implement RejectChanges() in DbContext
Story
There are many user requests for a function in DbContext class to reject or discard changes. See as well:
- https://stackoverflow.com/questions/5466677/undo-changes-in-entity-framework-entities
- https://stackoverflow.com/questions/16437083/dbcontext-discard-changes-without-disposing/16437305
Microsoft sample code: How to undo the changes in Entity Framework 4.1 and later
I first implemented a wrong version which I found online which caused terrible data loss. I was able to fix it with a similar solution as the Microsoft sample code is, see above.
Request
I would appreciate if a function DbContext.RejectChanges()
or a similar one would be implemented in the official version of Entity Framework Core.
Further technical details
EF Core version: 2.1.4 Database Provider: Microsoft.EntityFrameworkCore.SqlServer Operating system: Windows IDE: Visual Studio 2017 15.8.6
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Comments: 17 (1 by maintainers)
A use case I ran into:
My options are:
DbContext
isn’t holding onto anything transaction-wise.IServiceScopeFactory
and manually create a new scope every time I need to dump a DbContext state (which sure, isn’t often, but still).Issue with 1) is that EF Core doesn’t have a recommended way to even do this: https://github.com/aspnet/EntityFrameworkCore/issues/10694#issuecomment-357290795, so it’s both a recommended way to accomplish a task, while being unsupported.
I agree 2) is kind of gross, without the context being designed for that (at least that’s what I got from this issue), it may be doing some awful things we don’t want it to. If it was a first-class supported flow this is would be super easy.
try/catch
block that may need to throw out EF’s state having it’s own scope which is a bit rough.Maybe I’m just missing something… but it seems like all options have pretty poor downsides of either support or code maintainability, so I think some more supported solution to this should be considered a bit more.
@syndicatedshannon Thanks for the reply. As I mentioned, logging is simple an example and I’m aware of the proper way of implementing logging. After all, the original intention is about the necessity of a RejectChanges() method or some mechanism to reset the context to a ‘clean’ state. Retrieving a new context instance would probably suffice and function the same as resetting an existing context to the clean state.