Skip to content

3.1 Auditable

Josu Uribe edited this page Feb 6, 2019 · 1 revision

It's possible audit automatically all inserts/updates on a database, first use ModelBuilder.UseAudit().Build() extension method to create the columns, these columns will be created in all entities that implemente IAuditable interface. This method returns a IAudit interface that will be used later for fill these columns.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    /// Other builders...
    var audit = modelBuilder.UseAudit(Audit).Build();
}

You can use DbContext.SaveChanges() for ChangeTracker.Fill(Audit) extension method to be able to save data in the previously created columns.

public override int SaveChanges()
{
    ChangeTracker.FillAudit();
    return base.SaveChanges();
}

Also it's possible to parametrize the audit options using an object that implements IAudit interface.

modelBuilder.UseAudit(audit).Build();

Another options is parametrize Audit using built-in methods.

Audit = modelBuilder.UseAudit()
    .WithCreatedAt("CreatedAt", () => DateTime.Now)
    .WithUpdatedAt("UpdatedAt", () => DateTime.Now)
    .WithCreatedBy("CreatedBy", () => "Me")
    .WithUpdatedBy("UpdatedBy", () => "Yours")
    .Build();
Clone this wiki locally