Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get number of rows deleted and number of rows edited by DbContext.SaveChanges()

I use entity framework 6.1 with Code First approach. When I use DbContext.SaveChanges() as the result I can get

The number of objects written to the underlying database.

But is that possible to get advanced statistics: number of rows deleted, number of rows edited, number of rows added?

My supergoal is to get per-Entity staticstics.

Maybe before actually calling SaveChanges()..

like image 805
bairog Avatar asked Jan 10 '23 07:01

bairog


2 Answers

var modifiedCount = dbContext.ChangeTracker.Entries().Where(x => x.State == System.Data.EntityState.Modified).Count()

The above line of code can be used to fetch the modified entries, and similarly you can fetch the deleted and added too..

But you have to execute these lines of code before you call SaveChanges().

like image 164
Naga Sreenivas Avatar answered Feb 01 '23 18:02

Naga Sreenivas


You could use db.GetChangeSet(). This will contains three lists:

var deletes = db.GetChangeSet().Deletes;
var updates = db.GetChangeSet().Updates;
var inserts = db.GetChangeSet().Inserts;
var all = db.GetChangeSet().All;

This can be done before you submit the changes to the database.

Considering having a table called country

db.Tblcountries.InsertOnSubmit(
   new Tblcountry(){FkRegionId=1,CountryCode="US",Name="USA"});
var result= db.GetChangeSet().All.ToList();

The All list and the Insert list will contain this list:

PkCountryId Name CountryCode FkRegionId 
0           USA  US          1 

Reference:

  • DataContext.GetChangeSet Method
like image 37
Arion Avatar answered Feb 01 '23 16:02

Arion