CSharp · Console
// 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();
var customers = GenerateCustomers(5);
using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()))
{
connection.Open();
// SAVE customers
using (var bulk = new BulkOperation<Customer>(connection))
{
bulk.DestinationTableName = "Customers";
bulk.ColumnInputExpression = c => new { c.CustomerID, c.Name};
bulk.BulkInsert(customers);
}
// SAVE customers
using (var bulk = new BulkOperation<Customer>(connection))
{
bulk.DestinationTableName = "Customers";
bulk.IgnoreOnInsertExpression = c => new { c.ColumnToIgnore };
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() { Name = "Customer_" + i, ColumnToIgnore = "Ignore_" + 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,
[Name] [NVARCHAR](MAX) NULL,
[ColumnToIgnore] [NVARCHAR](MAX) NULL,
CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED
(
[CustomerID] ASC
)
)";
command.ExecuteNonQuery();
}
}
}
public class Customer
{
public int CustomerID { get; set; }
public string Name { get; set; }
public string ColumnToIgnore { get; set; }
}
}