DbContext ChangeTracker: Id of Added Entity for Au

2020-07-16 11:58发布

问题:

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

回答1:

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.



回答2:

Use GUIDs for primary key so your id's can be generated without hitting the database.