CSharp · Console
// 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.Collections.Generic;
using System.Data.SqlClient;
using Z.Dapper.Plus;
using System.Linq;
public class Program
{
public class Supplier
{
public int SupplierID {get;set;}
public string SupplierName {get;set;}
public Product Product {get;set;}
}
public class Product
{
public int ProductID {get;set;}
public string ProductName {get;set;}
public int SupplierID {get;set;}
}
public static void Main()
{
List<Supplier> suppliers = new List<Supplier>() { new Supplier() { SupplierName = "ExampleSupplierBulkInsert", Product = new Product() { ProductName = "ExampleProductBulkInsert" } }};
Console.WriteLine("ID of the new Supplier, before INSERT : " + suppliers.First().SupplierID);
DapperPlusManager.Entity<Supplier>().Table("Suppliers").Identity(x => x.SupplierID);
DapperPlusManager.Entity<Product>().Table("Products").Identity(x => x.ProductID);
using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
{
connection.BulkInsert(suppliers).ThenForEach(x => x.Product.SupplierID = x.SupplierID).ThenBulkInsert(x => x.Product);
}
Console.WriteLine("ID of the new Supplier, after INSERT : " + suppliers.First().SupplierID);
using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
{
FiddleHelper.WriteTable(connection.Query<Supplier>("Select TOP 10 * FROM Suppliers WHERE SupplierName = 'ExampleSupplierBulkInsert'").ToList());
FiddleHelper.WriteTable(connection.Query<Product>("Select TOP 10 * FROM Products WHERE ProductName = 'ExampleProductBulkInsert'").ToList());
// For see all Colum of Table, with one row.
FiddleHelper.WriteTable(connection.QueryFirstOrDefault("Select * FROM Suppliers WHERE SupplierName = 'ExampleSupplierBulkInsert'"));
// For see all Colum of Table, with one row.
FiddleHelper.WriteTable(connection.QueryFirstOrDefault("Select * FROM Products WHERE ProductName = 'ExampleProductBulkInsert'"));
}
}
}