EF Extensions - BatchSaveChanges - Documentation - BatchSaveChangesAsync(cancellationToken)

CSharp · Console

/Program.cs

// Entity Framework Extensions
// Doc: https://entityframework-extensions.net/batch-savechanges
// @nuget: Z.EntityFramework.Extensions
// @nuget: EntityFramework

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Data.Entity;
using System.Threading;
using System.Threading.Tasks;
					
public class Program
{	
	public static void Main()
	{
		MainAsync().Wait();
	}
	
	public static async Task MainAsync()
	{
		await GenerateCustomers();
		
		using (var context = new EntityContext())
		{
			CancellationTokenSource tcs = new CancellationTokenSource();
			CancellationToken token = new CancellationToken();
			
			var list = context.Customers.ToList();
			
			FiddleHelper.WriteTable("1 - Customers Before", context.Customers.AsNoTracking());
			
			// Modify "Customer_A"
			// Remove "Customer_B"
			// ADD "Customer_C"
			list.Single(x => x.Code == "Customer_A").Code = "Customer_A_Modified";
			context.Customers.Remove(list.Single(x => x.Code == "Customer_B"));
			context.Customers.Add(new Customer() { Code = "Customer_C" });
			
			await context.BatchSaveChangesAsync(token);
			
			Thread.Sleep(1000);
			tcs.Cancel();
			
			FiddleHelper.WriteTable("2 - Customers After", context.Customers.AsNoTracking());
		}
	}
	
	public static async Task GenerateCustomers()
	{
		using (var context = new EntityContext())
		{
			context.Customers.Add(new Customer() { Code = "Customer_A" });
			context.Customers.Add(new Customer() { Code = "Customer_B" });
			
			await context.BatchSaveChangesAsync();
		}
	}

	public class EntityContext : DbContext
	{
		public EntityContext() : base(FiddleHelper.GetConnectionStringSqlServer())
		{

		}
		
		public DbSet<Customer> Customers { get; set; }
	}
	
	public class Customer
	{
		public int CustomerID { get; set; }
		public string Code { get; set; }
	}
}
;