JohnFI
JohnFI

Reputation: 35

how to implement custom field with Audit.Net entityframework

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

Upvotes: 1

Views: 1934

Answers (1)

thepirat000
thepirat000

Reputation: 13114

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;
            })));

Upvotes: 3

Related Questions