I have a C# .NET Core API project with Entity Framework. In one of these APIs, there is a specific case where I need to abort the change I was making in my db context and then save other different data in my database.
I found and edited the code a little to do this:
public void RejectChanges()
{
var ChangeTracker = new Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker(_context);
foreach (var entry in ChangeTracker.Entries())
{
switch (entry.State)
{
case EntityState.Modified:
case EntityState.Deleted:
entry.State = EntityState.Modified; //Revert changes made to deleted entity.
entry.State = EntityState.Unchanged;
break;
case EntityState.Added:
entry.State = EntityState.Detached;
break;
}
}
}
It seems to work, but I have a very big doubt: if another API is going to save its own data, does this operation affect also its data, rejecting also those changes? Or, as I wish, does it affect only the API session that called this method?
EXAMPLE: API 1 edits some data in the context, then calls the RejectChanges
method. Meanwhile, the API 2 edits other data and it's going to save. Does RejectChanges
, called from API 1 reject also the edits made by API 2?
The Change Tracker is scoped to a single DbContext, which should be scoped to a single API request. Also you don't create a new ChangeTracker. The DbContext already has one.
var ChangeTracker = _context.ChangeTracker;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.