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

34 views Asked by At

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?

2

There are 2 answers

0
Yehor Androsov On

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)");
0
sa-es-ir On

You can get all the entities that already tracking by EF and then check their states.

In EF Core we have 5 states:

  • Added
  • Modified
  • Deleted
  • Unchanged
  • Detached
var entries = context.ChangeTracker.Entries();

foreach(var entry in entries)
{
  if(entry.State is EntityState.Added or EntityState.Modified or EntityState.Deleted)
  {
    // here you can count affected row
  }

}