I am using the Entity Framework to create a basic repository for adding / removing / updating client entries.
One thing I want is to be able to audit the client row so that I have a second CustomerAudit table that should receive the added record every time you add / update / delete the row. In old wyrld, this will be done using the database trigger when updating / deleting / pasting, etc. Now I am trying to do this by overriding the SaveChanges () method of the DBContext object using the ChangeTracker object and using this to create an audit record based on the data saved / updated with the current date time and the insert next to the actual row. The code is below.
The problem is that when updating or deleting, this works great when it writes the most recent record to the audit table, which will have either updated values or final values before deleting along with the current timestamp when this activity occurred.
When you add an entry, it inserts the entry into the audit table, but since the actual row has not yet been inserted (with an insert for identification), you do not have CustomerId yet and therefore it inserts the audit record using the correct data, but with CustomerId 0, which is not suitable for audit.
Any thoughts on how I can get my audience to work on adding posts?
public class CustomerDbContext : DbContext
{
public CustomerDbContext()
{
Database.SetInitializer(new CreateDatabaseIfNotExists<CustomerDbContext>());
}
public DbSet<Customer> Customers { get; set; }
public DbSet<CustomerAudit> CustomerAudits { get; set; }
public override int SaveChanges()
{
foreach (var ent in ChangeTracker.Entries().Where(p => p.State == System.Data.EntityState.Added || p.State == System.Data.EntityState.Deleted || p.State == System.Data.EntityState.Modified))
{
var auditRecord = GetAuditRecord(ent);
if (auditRecord != null)
CustomerAudits.Add(auditRecord);
}
return base.SaveChanges();
}
private static CustomerAudit GetAuditRecord(DbEntityEntry dbEntry)
{
var changedRecord = dbEntry.Entity as Customer;
return changedRecord == null ? null : new CustomerAudit(changedRecord);
}
}
source
share