how to implement custom field with Audit.Net entityframework

audit.net audit-trail c# entity-framework-core

Question

I'm new to Audit.net. I successfully configure it in my project.

But now, i need to extend it to save extra information like requesterID and a comment write on the view page.

my case : Entity mapped to Entity_AT

Entity {
    [Key]
    int     ID
    string  label
}
Entity_AT {
    [Key]
    int      ATID
    int      ID
    string   label
    int      ATFlag
    datetime ATCreationDate
    string   RequesterID
    string   ATComment
}
public void Add(TEntity obj, string RequesterId)
{
   _dbSet.Add(obj);
   _context.SaveChanges();
}
[AuditDbContext(Mode = AuditOptionMode.OptOut, IncludeEntityObjects = false, AuditEventType = "{database}_{context}")]
public class MyDBContext : AuditIdentityDbContext<ApplicationUser>
{
}
Audit.Core.Configuration.DataProvider = new EntityFrameworkDataProvider()
{
    AuditTypeMapper = t => t == typeof(Entity) ? typeof(Entity_AT) : null,
    AuditEntityAction = (evt, entry, auditEntity) =>
    {
        var a = (dynamic)auditEntity;
        a.ATCreationDate = DateTime.UtcNow;
        a.ATFlag = (entry.Action == "Insert") ? 1 : (entry.Action == "Update") ? 2 : (entry.Action == "Delete") ? 3 : 0;

        return true; // return false to ignore the audit
    }
};

I tried :

_context.AddAuditCustomField("RequesterId", requesterId);
_context.AddAuditCustomField("ATComment", "pippo");

_dbSet.Add(obj);
_context.SaveChanges();

but no results

1
1
3/25/2019 3:26:30 PM

Accepted Answer

You have added the "RequesterId" custom field to the AuditEvent, but you are not mapping it to the AuditEntity property.

You should do the following on the entity action:

Audit.Core.Configuration.DataProvider = new EntityFrameworkDataProvider()
{
    AuditTypeMapper = t => t == typeof(Entity) ? typeof(Entity_AT) : null,
    AuditEntityAction = (evt, entry, auditEntity) =>
    {
        var a = (dynamic)auditEntity;
        a.ATCreationDate = ...;
        a.ATFlag = ...;

        a.RequesterID = evt.CustomFields["RequesterId"] as string;
        a.ATComment = evt.CustomFields["ATComment"] as string;

        return true; 
    }
};

Note you can alternatively use the Fluent API to configure the data provider with a cleaner syntax:

Audit.Core.Configuration.Setup()
    .UseEntityFramework(_ => _
        .AuditTypeExplicitMapper(map => map
            .Map<Entity, Entity_AT>((evt, entry, auditEntity) =>
            {
                auditEntity.ATCreationDate = ...;
                auditEntity.ATFlag = ...;
                auditEntity.RequesterID = evt.CustomFields["RequesterId"] as string;
                auditEntity.ATComment = evt.CustomFields["ATComment"] as string;
            })));
0
3/26/2019 4:59:24 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow