First EF6 audit table per entity

I have a requirement that looks like it probably has a simpler solution with EF than what we are currently using.

Essentially, as an audit requirement for any entity that inherits from a given base class, I need to create both the entity table directly and a table that is identical but with three additional columns - FK back to the original entity table, description (e.g. "Modified", "Added", "Removed") and an XML column that will contain the serialized version of the object's state.

We are currently manually adding entities to create audit tables (they are currently inheriting from the AuditableEntity class and developers need to manually ensure that the other fields match the original object) and using migrations add T-SQL triggers to entity tables to update data in audit tables for any insert, update, delete.

I would prefer that I can somehow get EF to automatically create / migrate audit tables based on entity tables without having to manually synchronize them, and also use an interceptor or something similar to update the insert / update / delete audit table, while not using triggers. Does anyone know if this is possible or something similar? Earlier, the closest I came, this is a single general table of audit history, which was not so bad.

+3


source to share


2 answers


Disclaimer . I am the owner of an Entity Framework Plus project

This project can answer your requirements. You can access all of the audit information such as object name, action name, property name, original and current values, etc.

Lots of options are available, for example AutoSave all information in the database.



// 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)
    {
    }
}

      

Documentation: EF + Audit

+1


source


You can create one table with columns:

  • Id
  • TableName
  • Action (Add, Update, Remove)
  • IdOfRecord
  • XmlSerialized
  • DateChanges (use datetime2)


Then override SaveChanges () to write each change to a single table.

No need to fiddle with updating the audit table schema when doing migrations etc.

+1


source







All Articles