How to count DbSet rows added to in a DbContext

entity-framework-core

Question

Looked high and low but cannot find the syntax to count the number of rows in a [DbContext].[DbSet Entity] by the change status of the row. Specifically, I would like to know how many rows in one entity/table were added and are pending SaveChanges().

1
0
10/5/2016 4:41:52 PM

Accepted Answer

You can use one of the DbContext.ChangeTracker.Entries method overloads (similar to EF6):

var addedCount = db.ChangeTracker.Entries<YourEntity>()
    .Count(e => e.State == EntityState.Added);
1
10/5/2016 4:54:18 PM

Popular Answer

(First answer, so be gentle) I had a similar problem. One approach is to override the context SaveChanges method as proposed here: https://www.exceptionnotfound.net/entity-change-tracking-using-dbcontext-in-entity-framework-6/

But in your situation a special method on your context class might be more appropriate:

public virtual Tuple<int, int> CountChanges()
{
    var modified = ChangeTracker.Entries().Where(x => x.State == EntityState.Modified).Count();
    var added = ChangeTracker.Entries().Where(x => x.State == EntityState.Added).Count();
    return new Tuple<int, int>(modified, added);
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow