EF.Plus - Audit - Saving automatically by overriding SaveChanges & SaveChangesAsync (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.Threading;
using System.Threading.Tasks;

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
		   (context as EntityContext).AuditEntries.AddRange(audit.Entries);		

		// 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.IsActive == false ).ToList();
			var listToModify = context.Customers.Where(x => x.IsActive == true ).ToList();
			var listToAdd = new List<Customer>() { new Customer() { Name = "Customer_C", Description = "Description", IsActive = false}};
			 
			context.Customers.AddRange(listToAdd); // add
			context.Customers.RemoveRange(listToRemove); // remove
			listToModify.First().Description = "Updated_A"; // modify
			  
			context.SaveChanges(); 
		}
		
		
		using (var context = new EntityContext())
		{
			FiddleHelper.WriteTable("All Entry",context.AuditEntries.ToList());
			
			foreach(var entry in context.AuditEntries.ToList())
			{
				FiddleHelper.WriteTable("Properties for Entry ID: " + entry.AuditEntryID,context.AuditEntryProperties.Where(x => x.AuditEntryID == entry.AuditEntryID).ToList());
			}
		}
	}
		 
	public static void GenerateData()
	{
		
		using (var context = new EntityContext())
		{
			context.Customers.Add(new Customer() { Name ="Customer_A", Description = "Description", IsActive = true });
			context.Customers.Add(new Customer() { Name ="Customer_B", Description = "Description", IsActive = false });
			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<AuditEntry> AuditEntries { get; set; }
		public DbSet<AuditEntryProperty> AuditEntryProperties { get; set; }

		public DbSet<Customer> Customers { get; set; }
		
		public override int SaveChanges()
		{
			var audit = new Audit();
			audit.PreSaveChanges(this);
			var rowAffecteds = base.SaveChanges();
			audit.PostSaveChanges();

			if (audit.Configuration.AutoSavePreAction != null)
			{
				audit.Configuration.AutoSavePreAction(this, audit);
				base.SaveChanges();
			}

			return rowAffecteds;
		}

		public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken)
		{
			var audit = new Audit();
			audit.PreSaveChanges(this);
			var rowAffecteds = await base.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
			audit.PostSaveChanges();

			if (audit.Configuration.AutoSavePreAction != null)
			{
				audit.Configuration.AutoSavePreAction(this, audit);
				await base.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
			}

			return rowAffecteds;
		}
	}
	
	
	public class Customer
	{
		public int CustomerID { get; set; }
		public string Name { get; set; }
		public string Description { get; set; }
		public Boolean IsActive { get; set; }
	}
}
;