EF.Plus - Audit - Custom AuditEntry & Database First Approach (EF Core)

CSharp · Console

/Program.cs

// Entity Framework Plus
// Doc: https://entityframework-plus.net/audit

// @nuget: Microsoft.EntityFrameworkCore.SqlServer
// @nuget: Z.EntityFramework.Plus.EFCore

using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using Microsoft.Data.SqlClient;
using Z.EntityFramework.Plus;
using System.ComponentModel.DataAnnotations;

public class Program
{
	public static void Main()
	{
		using (var context = new EntityContext())
		{
			context.Database.EnsureCreated();
		}
		
		GenerateData();	
	
		AuditManager.DefaultConfiguration.AutoSavePreAction = (context, audit) =>
		{
			// ADD "Where(x => x.AuditEntryID == 0)" to allow multiple SaveChanges with same Audit
			var customAuditEntries = audit.Entries.Select(x => new DbAuditEntry(x)).ToList();
			(context as EntityContext).AuditEntries.AddRange(customAuditEntries);
		};
		
		// Audit : Easily tracks changes, exclude/include entity or property and auto save audit entries in the database.
		using (var context = new EntityContext())
		{
			var listToRemove = context.Customers.Where(x => x.CustomerName == "Customer_A" ).ToList();
			var listToModify = context.Customers.Where(x => x.CustomerName == "Customer_B" ).ToList();
			var listToAdd = new List<Customer>() { new Customer() { CustomerName = "Customer_C", ContactName = "Description"}};
			 
			context.Customers.AddRange(listToAdd); // add
			context.Customers.RemoveRange(listToRemove); // remove
			listToModify.First().ContactName = "Updated_A"; // modify
						
			Audit audit = new Audit();
			audit.CreatedBy = "ZZZ Projects"; // Optional 
			context.SaveChanges(audit);

			// Access to all auditing information
			var entries = audit.Entries;
		}
		
		using (var context = new EntityContext())
		{
			FiddleHelper.WriteTable("All Entry", context.AuditEntries.Include(x => x.Properties).AsNoTracking().ToList());
		} 
	}
		 
	public static void GenerateData()
	{
		
		using (var context = new EntityContext())
		{
			context.Customers.Add(new Customer() { CustomerName ="Customer_A", ContactName = "Description"});
			context.Customers.Add(new Customer() { CustomerName ="Customer_B", ContactName = "Description" });
			context.SaveChanges();	
		}
	}

	public class EntityContext : DbContext
	{
		public EntityContext() 
		{
		}

		protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
		{
			optionsBuilder.UseSqlServer(new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()));

			base.OnConfiguring(optionsBuilder);
		}
		
		public DbSet<DbAuditEntry> AuditEntries { get; set; }
		public DbSet<DbAuditEntryProperty> AuditEntryProperties { get; set; }
		public DbSet<Customer> Customers { get; set; }	
	}

	public class DbAuditEntry
	{
		public DbAuditEntry()
		{
		}
		public DbAuditEntry(AuditEntry entry)
		{
			EntitySetName = entry.EntitySetName;
			EntityTypeName = entry.EntityTypeName;
			State = entry.State;
			StateName = entry.StateName;
			CreatedBy = entry.CreatedBy;
			CreatedDate = entry.CreatedDate;
				
			Properties = entry.Properties.Select(x => new DbAuditEntryProperty(x)).ToList();
		}
		
		[Key]
		public int AuditEntryID { get; set; }
		public string EntitySetName { get; set; }
		public string EntityTypeName { get; set; }
		public AuditEntryState State { get; set; }
		public string StateName { get; set; }
		public string CreatedBy { get; set; }
		public DateTime CreatedDate { get; set; }
		public List<DbAuditEntryProperty> Properties { get; set; }
	}
	
	public class DbAuditEntryProperty
	{
		public DbAuditEntryProperty()
		{
		}
		public DbAuditEntryProperty(AuditEntryProperty property)
		{
			RelationName = property.RelationName;
			PropertyName = property.PropertyName;
			OldValue = property.OldValueFormatted;
			NewValue = property.NewValueFormatted;
		}
		
		[Key]
		public int AuditEntryPropertyID { get; set; }
		public string RelationName { get; set; }
		public string PropertyName { get; set; }
		public string OldValue { get; set; }
		public string NewValue { get; set; }
		
	}
	
	public class Customer
	{
		public int CustomerID { get; set; }
		public string CustomerName { get; set; }
		public string ContactName { get; set; }
	}
}
;