Dapper Tutorial - Dapper Plus - BulkInsert - Real Life Scenarios - Insert and keep identity value (NET Core)

CSharp · Console

/Program.cs

// Dapper Plus
// Doc: https://dapper-tutorial.net/bulk-insert

// @nuget: Dapper -Version 1.60.6
// @nuget: Z.Dapper.Plus
// @nuget: System.Data.SqlClient

using Dapper;
using System;
using System.Data;
using System.Collections.Generic;
using System.Data.SqlClient;
using Z.Dapper.Plus;
using System.Linq;
					
public class Program
{	
	public class Customer 
	{
		public int CustomerID {get;set;}
		public string CustomerName {get;set;}
		public string ContactName {get;set;}
		public string Address {get;set;}
		public string City {get;set;}
		public string PostalCode {get;set;}
		public string Country {get;set;}
	}
	
	public static void Main()
	{	
		List<Customer> customers = new List<Customer>();
		
		for (int i =0;i<200;i++)
		{
			customers.Add(new Customer() { CustomerID = 100 + i, CustomerName = "ExampleBulkInsert", ContactName = "Example Name :" +  i });
		}
		

		DapperPlusManager.Entity<Customer>().Table("Customers"); 
		
		using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
		{
			connection.UseBulkOptions(options => options.InsertKeepIdentity = true).BulkInsert(customers);
		}	
		
		
		using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
		{
			var customer = connection.Query<Customer>("Select * FROM CUSTOMERS WHERE CustomerName = 'ExampleBulkInsert'").ToList();
			
			Console.WriteLine("Row Insert : " + customer.Count());
			
			FiddleHelper.WriteTable(connection.Query<Customer>("Select TOP 10 * FROM CUSTOMERS WHERE CustomerName = 'ExampleBulkInsert'").ToList());
		}	
	}
}
;