EF Classic - Audit - Documentation - AuditManager.ExcludePropertyUnchanged(Func<object, bool> predicate)

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 which satisfy the predicate. Key properties are never excluded.
			this.Configuration.Audit.ExcludePropertyUnchanged(x => x.GetType() == typeof(Customer) && ((Customer)x).Description == "Description");
			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 which satisfy the predicate.
			context.Configuration.Audit.IncludePropertyUnchanged(x => x.GetType() == typeof(Customer) && ((Customer)x).Description == "Description");
			
			// 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(x => x.GetType() == typeof(Customer) && ((Customer)x).Description == \"Description\");", auditEntries.SelectMany(x => x.Properties));
		}
	}
	
	public class Customer
	{
		public int CustomerID { get; set; }
		public string Name { get; set; }
		public string Description { get; set; }
	}
}
;