EF Extensions - Home - Main Features - Bulk SaveChanges

CSharp · Console

/Program.cs

// Entity Framework Extensions - Main Features - Bulk SaveChanges
// Doc: https://entityframework-extensions.net/

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

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Data.SqlClient;
					
public class Program
{
	public static void Main()
	{
		// Just add "Bulk" prefix to "SaveChanges()"
		
		using (var context = new EntityContext())
		{
			context.Database.EnsureCreated();
		}
		
		// Easy to use
		using (var context = new EntityContext())
		{
			context.Customers.Add(new Customer() { Code = $"Info", Name = "Support Team", Email = "[email protected]" });
			context.Customers.Add(new Customer() { Code = $"Sales", Name = "Sales Team", Email = "[email protected]" });
			context.BulkSaveChanges();
			
			FiddleHelper.WriteTable("1 - Customers", context.Customers.ToList());
		}
		
		// Easy to customize
		using (var context = new EntityContext())
		{
			var customers = context.Customers.ToList();
			customers.ForEach(x => x.Name = "Best " + x.Name);

			context.BulkSaveChanges(options => options.BatchSize = 1000);
			
			FiddleHelper.WriteTable("2 - Customers (Updated)", context.Customers.Take(5).ToList());
		}
	}

	public class EntityContext : DbContext
	{
		public EntityContext() 
		{
		}
		
		public DbSet<Customer> Customers { get; set; }

		protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
		{
			optionsBuilder.UseSqlServer(new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()));

			base.OnConfiguring(optionsBuilder);
		}
	}

	public class Customer
	{
		public int CustomerID { get; set; }
		public string Code { get; set; }
		public string Name { get; set; }
		public string Email { get; set; }
	}
}
;