grefly
grefly

Reputation: 1199

Getting Newly Added Entities AFTER SaveChanges?

I have a process that needs the Primary Key ID of a newly added Entity every time an Entity is added. I have overriden the SaveChanges() method of DbContext, and looked at the ChangeTracker, but I don't see any dynamic way to retrieve the Entities that are newly added. Is there a good method to do so?

Upvotes: 0

Views: 737

Answers (2)

Eranga
Eranga

Reputation: 32437

Query the change tracker for new entities.

public override int SaveChanges()
{
    var newEntities = ChangeTracker.Entries()
                        .Where(entry => entry.State == EntityState.Added)
                        .Select(entry => entry.Entity).ToList();

    var count = base.SaveChanges();

    // do something with newEntities

    return count;
}

Upvotes: 3

Ocelot20
Ocelot20

Reputation: 10800

You can override SaveChanges and collect any entities in the Added state prior to the actual save, but that's about it AFAIK.

Upvotes: 1

Related Questions