4

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()..

2
  • I think the answer in this question will help you Commented Jul 3, 2014 at 6:56
  • Thx. I've missed that one Commented Jul 3, 2014 at 7:00

3 Answers 3

10
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().

Sign up to request clarification or add additional context in comments.

1 Comment

It should be System.Data.Entity.EntityState.Modified instead of System.Data.EntityState.Modified. At least for EF6. Edit suggestion from my part was rejected, but sofar I can see, the author possibly will never edit this... no activity since 2014... and on the other hand my comment probably will disappear some day and someone else might suggest the same? Weird reviewing system. But to follow the reviewers reasonings, now shared as a comment ^^
1

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:

1 Comment

GetChangeSet() is for Linq-to-SQL (the predecessor to Linq-to-Entities and Entity Framework), it isn't present in Entity Framework that the OP is asking about.
-2

According to the documentation, the return value of DbContext.SaveChanges is

The number of objects written to the underlying database.

So what you see is only possible, when no entities needed to be saved to the database.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.