Menu

Advance auditing – audit every entity using EntityFramework-Plus

In one of my previous tutorials I talked about simple auditing, that records the Created By And Edited By user, but that is not enough in most cases. You will have to audit every entity, and what was the previous value and current value. This would be a real deal if you try to do it yourself, but I do not want to reinvent the wheel. That is where the EntityFramework-Plus audit comes handy.

In your DbContext define the audit entities.

public class QuestionsContext : DbContext
{
   public QuestionsContext (IConfigurationRoot config, DbContextOptions options) : base(options)
   {
            _config = config;           
   }
   public DbSet<AuditEntry> AuditEntries { get; set; }
   public DbSet<AuditEntryProperty> AuditEntryProperties { get; set; }
   public DbSet<Question> Questions { get; set; }
   ...
   ....
}

Excluding auditing some fields from audit and audit only fields that has changed.

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.RemovePluralizingTableNameConvention();
            modelBuilder.HasDefaultSchema(DefaultSchema);

            base.OnModelCreating(modelBuilder);

            AuditManager.DefaultConfiguration.AutoSavePreAction = (context, audit) =>
            {
                var activitiesContext = context as ActivitiesContext;
                if (activitiesContext != null) activitiesContext.AuditEntries.AddRange(audit.Entries);
            };

            AuditManager.DefaultConfiguration.IgnorePropertyUnchanged = true; // audit only changed fields
            AuditManager.DefaultConfiguration.ExcludeProperty<ICreateEntityBase>(p => new { p.CreatedBy, p.CreatedOn }); // ignore this field
            AuditManager.DefaultConfiguration.ExcludeProperty<IModifyEntityBase>(p => new { p.ModifiedBy, p.ModifiedOn }); // ignore this field
        }

Now override SaveChanges()

 public override int SaveChanges()
        {
            var currentUser = // username;
            var hoDateTime = // date;
           
            var audit = new Audit
            {
                CreatedBy = currentUser
            };           
                      
            audit.PreSaveChanges(this);
            var rowsAffected = base.SaveChanges();
            audit.PostSaveChanges();

            if (audit.Configuration.AutoSavePreAction != null)
            {
                audit.Configuration.AutoSavePreAction(this, audit);
                base.SaveChanges();
            }

            return rowsAffected;
        }

Now this will audit every entity, every field that changed.

 

Leave a comment