EF Extensions - BulkUpdate - Update Only Specific Properties

CSharp · Console

/Program.cs

// Entity Framework Extensions
// Doc: https://entityframework-extensions.net/bulk-update

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

using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
					
public class Program
{
	public static void Main()
	{
		using (var context = new EntityContext())
		{
			context.Database.EnsureCreated();
		}
		
		SeedCustomers(5);

		// Update Only Specific Properties
		using (var context = new EntityContext())
		{
			var customers = context.Customers.Take(3).ToList();
			customers.ForEach(c => {
				c.Code += "_Updated";
				c.Name += "_Updated";
			});
			
			FiddleHelper.WriteTable("1 - Customers Before", context.Customers.AsNoTracking());
			
			// Update only specific properties
			context.BulkUpdate(customers, options => options.ColumnInputExpression = x => new
				{
					x.Name
				});
			
			// Ignore specific properties
			// context.BulkUpdate(customers, options => options.IgnoreOnUpdateExpression = x => x.Code);

			FiddleHelper.WriteTable("2 - Customers After", context.Customers.AsNoTracking());;
		}	
	}
	
	public static List<Customer> GenerateCustomers(int count, bool useOld = false) 
	{
		List<Customer>  list = new List<Customer>();
		
		for(int i = 0; i < count; i++)
		{
			list.Add(new Customer() { CustomerID = (i + 1), Code = "Code_" + i, Name = "Customer_" + i});
		}
		
		return list;
	}
	
	public static void SeedCustomers(int count) 
	{
		var customers = GenerateCustomers(count, true);
		new EntityContext().BulkInsert(customers);
	}
}

/EntityContext.cs

using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;

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 Code { get; set; }
	public string Name { get; set; }
}
;