EF - SPLIT SaveChanges into Multiple Batches

CSharp · Console

/Program.cs

// @nuget: EntityFramework

using System;
using System.Data.Entity;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
					
public class Program
{
	public static void Main()
	{
		int batchSize = 400;
		
		var context = new EntityContext();
		
		for(int i = 0; i <= 2000; i++)
		{
			if (i != 0 && i%batchSize == 0)
    		{
        		context.SaveChanges();
        		context = new EntityContext();
    		}
			
			var customer = new Customer();
			customer.Name ="Customer_" + i;

			context.Customers.Add(customer);
		}

		context.SaveChanges();
		
		Console.WriteLine(context.Customers.Count());

		FiddleHelper.WriteTable(context.Customers.Take(5).ToList());
		
	}
	

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