Bulk Operations - BulkMerge - Real Life Scenarios - BulkMerge with custom key (Entity)

CSharp · Console

/Program.cs

// Bulk Operations
// Doc: https://bulk-operations.net/bulk-merge

// @nuget: Z.BulkOperations

using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using Z.BulkOperations;
				
public class Program
{
	public static void Main()
	{
		GenerateDatabase();
		
		SeedCustomers(2);
		
		var customers = GenerateCustomers(5);
		
		using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()))
		{
			connection.Open();
			
			// SHOW data
			ShowData(connection, "Before");
			
			// SAVE customers
			using (var bulk = new BulkOperation<Customer>(connection))
			{
				bulk.DestinationTableName = "Customers";
				bulk.AutoMapKeyExpression = c => c.Code;
				bulk.BulkMerge(customers);
			}

			// SHOW data
			ShowData(connection, "After");
		}
	}
	
	public static void ShowData(SqlConnection connection, string text)
	{
		// SHOW data
		using (var command = connection.CreateCommand())
		{
			command.CommandText = @"
SELECT * FROM Customers
";
			var ds = new DataSet();
			var sqlDataAdapter = new SqlDataAdapter(command);
			sqlDataAdapter.Fill(ds);

			ds.Tables[0].TableName = "1 - Customers " + text;

			FiddleHelper.WriteTable(ds.Tables[0]);
		}
	}
	
	public static List<Customer> GenerateCustomers(int count, bool useOld = false) 
	{
		List<Customer>  list = new List<Customer>();
		
		for(int i = 0; i < count; i++)
		{
			list.Add(new Customer() { Code = "Z" + (i + 1), Name = (useOld ? "Old_" : "") + "Customer_" + i});
		}
		
		return list;
	}
	
	public static void SeedCustomers(int count) 
	{
		var customers = GenerateCustomers(count, true);
		using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()))
		{
			connection.Open();
			
			// SAVE customers
			using (var bulk = new BulkOperation<Customer>(connection))
			{
				bulk.DestinationTableName = "Customers";

				bulk.BulkInsert(customers);
			}
		}
	}
	
	public static void GenerateDatabase()
	{
		using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()))
		{
			connection.Open();
			using (var command = connection.CreateCommand())
			{
				command.CommandText = @"   
CREATE TABLE [Customers]
(
	[CustomerID] [INT] IDENTITY(1,1) NOT NULL,
	[Code] [NVARCHAR](MAX) NULL,
	[Name] [NVARCHAR](MAX) NULL,
	CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED 
	(
		[CustomerID] ASC
	)
)";
				command.ExecuteNonQuery();
			}
		}
	}
	
	public class Customer
	{
		public int CustomerID { get; set; }
		public string Code { get; set; }
		public string Name { get; set; }
	}
}
;