EF Classic - BulkInsert - Documentation - BulkInsertAsync(items, cancellationToken)

CSharp · Console

/Program.cs

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

// @nuget: Z.EntityFramework.Classic

using System.Collections.Generic;
using System.Data.Entity;
using System.Threading.Tasks;
using System.Threading;

public class Program
{	
	public static void Main()
	{
		MainAsync().Wait();
	}
	
	public static async Task MainAsync()
	{
		var customers = GenerateCustomers(5);

		using (var context = new EntityContext())
		{
			FiddleHelper.WriteTable("1 - Customers Before", context.Customers);
			
			CancellationTokenSource tcs = new CancellationTokenSource();
			CancellationToken token = new CancellationToken();
			
			// Easy to customize
			await context.BulkInsertAsync(customers, token);
			
			Thread.Sleep(1000);
			tcs.Cancel();
			
			FiddleHelper.WriteTable("2 - Customers After", context.Customers);
		}	
	}
	
	public static List<Customer> GenerateCustomers(int count) 
	{
		List<Customer>  list = new List<Customer>();
		
		for(int i = 0; i < count; i++)
		{
			list.Add(new Customer() { Name ="Customer_" + i});
		}
		
		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; }
	}
}
;