EF Classic - Audit - Documentation - AuditManager.ExcludePropertyUnchanged<TEntityType>()

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 Z.EntityFramework.Classic;

public class Program
{
	public class EntityContext : DbContext
	{
		public EntityContext() : base(FiddleHelper.GetConnectionStringSqlServer())
		{
			// Add your configuration here
			// Excludes from the audit all properties unchanged from entities of type 'TEntityType' type. Key properties are never excluded. 
			this.Configuration.Audit.ExcludePropertyUnchanged<Customer>();
			this.Configuration.Audit.AutoSaveSet = this.XmlAuditEntries;
			this.Configuration.Audit.IsEnabled = true;
		}
		
		public DbSet<Customer> Customers { get; set; }
		public DbSet<XmlAuditEntry> XmlAuditEntries { get; set; }
	}
	
	public static void Main()
	{
		using (var context = new EntityContext())
		{
			context.Configuration.Audit.IsEnabled = false;
			context.Customers.Add(new Customer() { Name = "Customer_A", Description = "Description" });
			
			// Save changes with Audit Enabled
			context.SaveChanges();
		}
				
		using (var context = new EntityContext())
		{
			context.Customers.ToList().ForEach(x => x.Description = "Update_1");
			
			// Save changes with Audit Enabled
			context.SaveChanges();
			// Display Audit Properties Trail
			var auditEntries = context.XmlAuditEntries.ToAuditEntries();
			FiddleHelper.WriteTable("1 - Entity Framework - All Unchanged Property Exclude (Key properties are never excluded);", auditEntries.SelectMany(x => x.Properties));
		}
		
		using (var context = new EntityContext())
		{			
			context.Customers.ToList().ForEach(x => x.Description = "Update_2");
			
			// Includes to the audit all properties unchanged from entities of type 'TEntityType' type.
			context.Configuration.Audit.IncludePropertyUnchanged<Customer>();
			
			// Save changes with Audit Enabled
			context.SaveChanges();
			
			// Display Audit Properties Trail
			var auditEntries = context.XmlAuditEntries.ToAuditEntries();
			FiddleHelper.WriteTable("2 - Entity Framework - context.Configuration.Audit.IncludePropertyUnchanged<Customer>();", auditEntries.SelectMany(x => x.Properties));
		}
	}
	
	public class Customer
	{
		public int CustomerID { get; set; }
		public string Name { get; set; }
		public string Description { get; set; }
	}
}
;