Reputation: 704
We are using https://github.com/bilal-fazlani/tracker-enabled-dbcontext
to create an audit trail of changes. We'd also like to record inserts into the trail of new records. we can loop though the entities just added but there seems to be no way of getting the ID for the entity just added?
A year ago there was an article written suggesting it's a limitation / not possible - https://www.exceptionnotfound.net/entity-change-tracking-using-dbcontext-in-entity-framework-6/
but there are also some comments suggesting there is a way. we studied those and the related code but are not any clearer, is it actually possible to audit inserts properly with this framework?
foreach (var entryAdded in addedEntities)
{
var entityKeyObject = objectContext.ObjectStateManager.GetObjectStateEntry(entryAdded.Entity).EntityKey;
var entityKey = entityKeyObject.EntityKeyValues.Length >= 1 ? entityKeyObject.EntityKeyValues[0].Value : 0;
// insert into audit log here..
}
Upvotes: 0
Views: 491
Reputation: 11347
Yes, it's possible to get inserted ID for entity just added.
In short, you simply need to handle two events:
All the codes can be found using the link. So I cannot answer how to make it with this library but at least, I can ensure you at 100% it's possible.
One alternative is using another Entity Framework Audit Library
Disclaimer: I'm the owner of the project Entity Framework Plus
Wiki: EF+ Audit
This library allows you to audit & save information in a database. By default, it already supports ID added.
// using Z.EntityFramework.Plus; // Don't forget to include this.
var ctx = new EntityContext();
// ... ctx changes ...
var audit = new Audit();
audit.CreatedBy = "ZZZ Projects"; // Optional
ctx.SaveChanges(audit);
// Access to all auditing information
var entries = audit.Entries;
foreach(var entry in entries)
{
foreach(var property in entry.Properties)
{
}
}
Upvotes: 0