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:

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)

Most upvoted comments

A use case I ran into:

  • Attempting to do a lot of EF work
  • Upon error, create a log entry and log it to the database
  • If an error happens in the middle of EF work, the EF state will be invalid (missing objects, not cleaned out other objects, etc.)
  • Log insert usually fails due to prior state

My options are:

  • Inject a DbContext factory instead of a DbContext, request a new instance from the factory when logging errors, pray that the original DbContext isn’t holding onto anything transaction-wise.
  • Loop through the change tracker dropping everything.
  • Inject the entire 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.

  1. Is probably the “most DI friendly” while basically requiring us to be very explicit in scope, within basically every 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.