Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DbContext ChangeTracker: Id of Added Entity for Auditing

I have something like this:

public override int SaveChanges()
{
    foreach (var changeLog in this.ChangeTracker.Entries()
        .Where(p => p.State == EntityState.Added ||
               p.State == EntityState.Deleted ||
               p.State == EntityState.Modified)
        .SelectMany(entity => AuditRecords(entity)))
    {
        this.ChangeLogs.Add(changeLog);
    }

    return base.SaveChanges();
}

But, of course, audited change logs will not contain the primary key value of the entity when the EntityState is Added (until after SaveChanges). How can I obtain the primary key value for change auditing purposes?

Richard

like image 316
Richard Avatar asked Mar 14 '12 01:03

Richard


1 Answers

I'd store the references to the entities in a List<T> (or an array, or other such structure) and then make the call to the underlying implementation of SaveChanges.

When the call is complete, because your entities are reference types (best practices indicate they should be as they are mutable), the primary keys on those items in the list should be populated, at which point you can pass the list of changed entities to your audit layer.

Also, it appears that you are trying to add an entity that one Entity type and add it to another Entity type collection (whatever is exposed by ChangeLogs); I'd recommend against this. If you are entering items in another entity set, do not reuse those entities, but copy the instances to the proper entity type.

like image 50
casperOne Avatar answered Sep 30 '22 13:09

casperOne