Search code examples
.netentity-framework-coreef-core-8.0

Entity Framework: Find Number Of Rows That Will Be Affected By A Change


Using Entity Framework (8.0.3), I'm looking to find the number of rows that would be affected, should one call DbContext.SaveChanges(), without actually saving the changes to the database, to be implemented something along the lines of this:

int numberOfChanges = MyDbContext.NumberOfChanges;
Console.WriteLine($"Save {numberOfChanges} changes? (y/n)");
if (Console.ReadKey() == 'y') 
{ // ...

I've looked through my class that implements DbContext and found nothing that suggests a representation of the number of altered rows.

My ideas to solve this include:

  • Taking a "snapshot" of the database as it was, saving changes, extracting the number of rows affected, then re-setting the database to how it was before (slow, memory-intensive, and requires extra code maintenance)
  • Using a custom getter/setter on every DbSet<T> in the implementation of DbContext (messy, and again requires extra maintenance in expanding the implementation)

Is there a better way to find the number of changes that will be made on a DbContext.SaveChanges() call?


Solution

  • You can find out what was changed via dbContext.ChangeTracker.Entries(). In your case it could look something like

    int numberOfChanges = MyDbContext.ChangeTracker.Entries().Count();
    Console.WriteLine($"Save {numberOfChanges} changes? (y/n)");