Bulk Operations - BulkInsert - Real Life Scenarios - Insert only if the entity not already exists (Entity) (NET Core)

CSharp · Console

/Program.cs

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

// @nuget: Z.BulkOperations
// @nuget: System.Data.SqlClient

using System;
using System.Data;
using Z.BulkOperations;
using System.Data.SqlClient;
using System.Collections.Generic;
					
public class Program
{
	public static void Main()
	{
		GenerateDatabase();
		
		using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()))
		{
			connection.Open();
			
			var customers = GenerateCustomers(3);
			
			// SAVE customers
			using (var bulk = new BulkOperation<Customer>(connection))
			{
				bulk.DestinationTableName = "Customers";

				bulk.BulkInsert(customers);
			}
			
			customers = GenerateCustomers(5);
			
			// SAVE customers
			using (var bulk = new BulkOperation<Customer>(connection))
			{
				bulk.DestinationTableName = "Customers";
				bulk.InsertIfNotExists = true;
				bulk.AutoMapKeyExpression = c => c.Code;
				
				// Customer "C_0", "C_1", "C_2" already exists
				// Customer "C_3", "C_4" are added
				bulk.BulkInsert(customers);
			}
			
			// 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";
				
				FiddleHelper.WriteTable(ds.Tables[0]);
			}
		}
	}
	
	public static List<Customer> GenerateCustomers(int count) 
	{
		List<Customer>  list = new List<Customer>();
		
		for(int i = 0; i < count; i++)
		{
			list.Add(new Customer() { CustomerID = 100 + i, Code = "C_" + i, Name = "Customer_" + i});
		}
		
		return list;
	}
	
	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; }
	}
}
;