.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:

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)");