EF Classic - Audit - Getting Started - AutoSave Action (EF Core)

CSharp · Console

/Program.cs

// Entity Framework Classic
// Doc: https://entityframework-classic.net/audit

// @nuget: Z.EntityFramework.Classic

using System;
using System.Linq;
using System.Collections.Generic;
using System.Data.Entity;
using System.Text;
using Z.EntityFramework.Classic;

public class Program
{
	public class EntityContext : DbContext
	{
		public EntityContext() : base(FiddleHelper.GetConnectionStringSqlServer())
		{
			// Add your configuration here
			this.Configuration.Audit.AutoSaveAction = (context, auditing) => {
				foreach(var entry in auditing.EntriesXml)
				{
					Log.AppendLine("EntitySetName: " + entry.EntitySetName);
					Log.AppendLine("EntityTypeName: " + entry.EntityTypeName);
					Log.AppendLine("State: " + entry.State);
					Log.AppendLine("StateName: " + entry.StateName);
					Log.AppendLine("CreatedBy: " + entry.CreatedBy);
					Log.AppendLine("CreatedDate: " + entry.CreatedDate);
					Log.AppendLine("XmlProperties: ");
					Log.AppendLine(entry.XmlProperties);
					Log.AppendLine("---");
					Log.AppendLine("---");
					Log.AppendLine("---");
				}				
			};
			this.Configuration.Audit.IsEnabled = true;
		}
		
		public DbSet<Customer> Customers { get; set; }
	}
	
	public static StringBuilder Log = new StringBuilder();
	
	public static void Main()
	{
		using (var context = new EntityContext())
		{
			context.Customers.Add(new Customer() { Name = "Customer_A", Description = "Description" });
			context.Customers.Add(new Customer() { Name = "Customer_B", Description = "Description" });			
			context.Customers.Add(new Customer() { Name = "Customer_C", Description = "Description" });
			
			// Save changes with Audit Enabled
			context.SaveChanges();
		}
		
		// Display Audit Trail
		Console.WriteLine(Log.ToString());
	}

	public class Customer
	{
		public int CustomerID { get; set; }
		public string Name { get; set; }
		public string Description { get; set; }
	}
}
;