EF Classic - Bulk Insert - Performance Comparison

CSharp · Console

/Program.cs

// Entity Framework Classic
// Doc: https://entityframework-classic.net/bulk-insert

// @nuget: Z.EntityFramework.Classic

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Data.Entity;

public class Program
{
	public static List<BenchmarkResult> BenchmarkResults = new List<BenchmarkResult>();
	
	public static void Main()
	{
		JustInTime_Compile();
		
		// Generate X customers
		var customers = GenerateCustomers(1000);
		
		var clockSaveChanges = new Stopwatch();
		var clockBulkInsert = new Stopwatch();
		
		using (var context = new EntityContext())
		{
			// SaveChanges
			context.Customers.AddRange(customers);
			clockSaveChanges.Start();
			context.SaveChanges();
			clockSaveChanges.Stop();

			BenchmarkResults.Add(new BenchmarkResult() { Action = "SaveChanges (EF)", Entities = customers.Count, Performance = clockSaveChanges.ElapsedMilliseconds + " ms" });
		}
		
		using (var context = new EntityContext())
		{
			// BulkInsert
			clockBulkInsert.Start();
			context.BulkInsert(customers, options => options.AutoMapOutputDirection = false); // performance can be improved with options
			clockBulkInsert.Stop();

			BenchmarkResults.Add(new BenchmarkResult() { Action = "BulkInsert (EF Classic)", Entities = customers.Count, Performance = clockBulkInsert.ElapsedMilliseconds + " ms" });
		}
		
		FiddleHelper.WriteTable(BenchmarkResults);
	}
		 
	public static void JustInTime_Compile()
	{
		var customers = GenerateCustomers(20);
		
		// SaveChanges
		using (var context = new EntityContext())
		{
			context.Customers.AddRange(customers);
			context.SaveChanges();
			
			// Clean
			context.BulkDelete(customers);
		}

		// BulkInsert
		using (var context = new EntityContext())
		{
			context.BulkInsert(customers, options => options.AutoMapOutputDirection = false);
			
			// Clean
			context.BulkDelete(customers);
		}
	}
	
	public static List<Customer> GenerateCustomers(int count)
	{
		var list = new List<Customer>();
		
		for(int i = 0; i < count; i++)
		{
			list.Add(new Customer() { Name = "Customer_" + i, Description = "Description_" +  i, IsActive = i % 2 == 0 });
		}

		return list;
	}

	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; }
		public string Description { get; set; }
		public Boolean IsActive { get; set; }
	}
	
	public class BenchmarkResult
	{
		public string Action { get; set; }
		public int Entities { get; set; }
		public string Performance { get; set; }
	}
}
;