Search code examples
c#audit.net

Audit.NET - Entity Framework - How to Implement OptOut


I'm in the process of implementing Auditing with Audit.NET and Entity Framework with an MVC application running .NET 4.6.1. I was able to configure auditing via startup so that it captures audit information and logs it to a custom AuditLog table using the JSON example to store the entire model. Currently this implementation is working, however, I want to be able to use OptOut so that I can specifically define models to be audited via the [AuditInclude] attribute.

Below is my code for the audit configuration and I've defined my context as OptOut but it's still logging all database interactions.

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.Now;
                            entity.AuditUser = Environment.UserName;
                            entity.TablePk = entry.PrimaryKey.First().Value.ToString();
                        })
                    .IgnoreMatchedProperties(true));

DBContext

[AuditDbContext(Mode =AuditOptionMode.OptOut)]
    public class DbContext : AuditDbContext

Does anyone know how to implement OptOut with this configuration of Audit.NET?


Solution

  • The reason that it was not working is that I had specified the incorrect AuditOptionMode. It should have been AuditOptionMode.OptIn. I mistakenly thought that when you specify AuditOptionMode.OptOut that it's telling the framework that you want to OptOut of auditing. However, this actually tells the framework that you wish to specifically OptOut any entities that you don't want to be audited. The IntelliSense explains this nicely, I just missed it.

    When doing this it works via the Attribute definition and also via the constructor as suggested by gev125.

    [AuditDbContext(Mode = AuditOptionMode.OptIn)]
    

    or

    public DBContext() 
    {
         Mode = AuditOptionMode.OptIn;
    }