Only saving audit.net when updating or deleting, not when creating a new DB entry

21 Views Asked by At

I am using Audit.Net with EF. I would like to only save into the audit table when a record is updated or deleted. When new entries are done, i don't need it as the records contain the date and user name already.

My Program.cs settings:

Audit.Core.Configuration.Setup()
    .UseEntityFramework(ef => ef
        .AuditTypeMapper(t => typeof(AuditLog))
        .AuditEntityAction<AuditLog>((ev, entry, entity) =>
        {
            entity.AuditData = entry.ToJson();
            entity.EntityType = entry.EntityType.Name;
            entity.AuditDate = DateTime.UtcNow;
            entity.AuditUserName = ev.CustomFields["UserName"].ToString();
            entity.AuditUserNID = ev.CustomFields["UserNID"].ToString();
            entity.AuditUserEmail = ev.CustomFields["UserEmail"].ToString();
            entity.TablePk = entry.PrimaryKey.First().Value.ToString();
        })
    .IgnoreMatchedProperties(true));

my DBContext.cs :

public class NodeDBContext(DbContextOptions options) : AuditDbContext(options)
...

the auditlog table:

public class AuditLog
{
    public Guid Id { get; set; }
    public string AuditData { get; set; }
    public string EntityType { get; set; }
    public DateTime AuditDate { get; set; }
    public string AuditUserName { get; set; }
    public string AuditUserNID { get; set; }
    public string AuditUserEmail { get; set; }
    public string TablePk { get; set; }
}

As you can see i do not use an override on the save method, so ideally i would want to somehow indicate this "not saving" for new entries in the setup in my program.cs

Is that possible?

And if not, what would be the best solution doing it in a different way?

Thanks

1

There are 1 best solutions below

0
thepirat000 On BEST ANSWER

You can make your AuditEntityAction to return a boolean indicating whether to include the entity.

For example:

Audit.Core.Configuration.Setup()
    .UseEntityFramework(ef => ef
        .AuditTypeMapper(t => typeof(AuditLog))
        .AuditEntityAction<AuditLog>((ev, entry, entity) =>
        {
            if (entry.Action == "Insert")
            {
                return false;
            }
            
            entity.EntityType = entry.EntityType.Name;
            entity.AuditDate = DateTime.UtcNow;
            // ...
            return true;
        }));