EFE - IgnoreOnUpdateMatchedAndOneNotConditionNames (EF Core)

CSharp · Console

/Program.cs

// Entity Framework Extensions
// Doc: https://entityframework-extensions.net/matched-and-one-not-condition

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

using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using Microsoft.Data.SqlClient;
using Z.BulkOperations;

public class Program
{
	public static void Main()
	{
		// SCENARIO: https://entityframework-extensions.net/matched-and-one-not-condition
		
		// CREATE & SEED
		using (var context = new EntityContext())
		{
			context.Database.EnsureCreated();
			
			var customers = new List<Customer>();
			
			customers.Add(new Customer() { CustomerID = 1, Name = "Jonathan", Email = "Email_Jonathan", Note = "Note_Jonathan" });
            customers.Add(new Customer() { CustomerID = 2, Name = "Mikael", Email = "Email_Mikael", Note = "Note_Mikael" });
            customers.Add(new Customer() { CustomerID = 3, Name = "Sara", Email = "Email_Sara", Note = "Note_Sara" });
			
			context.BulkInsert(customers, options => { options.InsertKeepIdentity = true; });
			
			FiddleHelper.WriteTable("1 - Before BulkUpdate", context.Customers.ToList());
		}

		using (var context = new EntityContext())
		{
			var customers = new List<Customer>();
			
			// DATA coming from an importation
			
			// "Jonathan" only have the "Note" property updated
			customers.Add(new Customer() { CustomerID = 1, Name = "Jonathan", Email = "Email_Jonathan", Note = "Note_Jonathan (Updated)" });
			customers.Add(new Customer() { CustomerID = 2, Name = "Mikael (Updated)", Email = "Email_Mikael (Updated)", Note = "Note_Mikael (Updated)" });
			customers.Add(new Customer() { CustomerID = 3, Name = "Sara (Updated)", Email = "Email_Sara (Updated)", Note = "Note_Sara (Updated)" });
			
			context.BulkUpdate(customers, options => 
			{
				// ON UPDATE, modify the customer if a values for "Name" or "Email" is different (by excluding other properties)
			    options.IgnoreOnUpdateMatchedAndOneNotConditionNames = new List<string>() { nameof(Customer.Note) };
			});
			
			FiddleHelper.WriteTable("2 - After BulkUpdate", context.Customers.AsNoTracking().ToList());
		}
	}
	
	public class EntityContext : DbContext
	{
		public EntityContext() 
		{
		}

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

			base.OnConfiguring(optionsBuilder);
		}
		
		public DbSet<Customer> Customers { get; set; }
	}
	
	public class Customer
	{
		public int CustomerID { get; set; }
		public string Name { get; set; }
		public string Email { get; set; }
		public string Note { get; set; }
	}
}
;