I think Audit.NET library with its EntityFramework extension can help you for this kind of requirement, because you will need minimal changes to your code.
For example, let say you have the following context:
public class YourContext : DbContext
{
public DbSet<Post> Posts { get; set; }
}
And you want to audit changes when the Date
field of Posts
table is about to be set to NULL
.
First you need to change the base class of your context to inherit from Audit.EntityFramework.AuditDbContext
:
public class YourContext : AuditDbContext
{
public DbSet<Post> Posts { get; set; }
}
Then it's just a matter of startup configuration, for example:
// Configure the event output to save logs as files
Audit.Core.Configuration.Setup().UseFileLogProvider(_ => _.Directory(@"D:\Temp"));
// Add a custom action to filter out the events
Audit.Core.Configuration.AddCustomAction(ActionType.OnScopeCreated, scope =>
{
var ef = scope.Event.GetEntityFrameworkEvent();
var interested = ef.Entries.Any(e => e.Table == "Posts"
&& new[] { "Insert", "Update" }.Contains(e.Action)
&& e.ColumnValues["Date"] == null);
// Discard the audit event if we are not interested in (i.e. only log when Date is null)
if (!interested)
{
scope.Discard();
}
});
// Configure EF extension
Audit.EntityFramework.Configuration.Setup()
.ForContext<YourContext>() // Your context class type
.UseOptIn() // OptIn to include specific entities
.Include<Post>(); // Audit only the Post entity
With this configuration, it will be generating json files on your file system with a content similar to the following:
{
"EventType": "YourContext",
"Environment": {
"UserName": "Federico",
"MachineName": "HP",
"DomainName": "Domain",
"Exception": null,
"Culture": "en-US"
},
"StartDate": "2017-09-10T16:11:05.7987461-05:00",
"EndDate": "2017-09-10T16:11:10.4458419-05:00",
"Duration": 4647,
"EntityFrameworkEvent": {
"Database": "Blogs",
"Entries": [
{
"Table": "Posts",
"Action": "Insert",
"PrimaryKey": {
"Id": 11
},
"ColumnValues": {
"Id": 11,
"BlogId": 7,
"Content": "post content",
"Date": null,
"Title": "post-test"
},
"Valid": true
}
],
"Result": 2,
"Success": true
}
}