CSharp · Console
// Entity Framework Classic
// Doc: https://entityframework-classic.net/bulk-insert
// @nuget: Z.EntityFramework.Classic
using System.Data.Entity;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var customers1 = GenerateCustomers(0, 5);
var customers2 = GenerateCustomers(5, 5);
using (var context = new EntityContext())
{
FiddleHelper.WriteTable("1 - Customers Before", context.Customers);
// Easy to use
context.BulkInsert(customers1);
// Easy to customize
context.BulkInsert(customers2, options => options.BatchSize = 100);
FiddleHelper.WriteTable("2 - Customers After", context.Customers);
}
}
public static List<Customer> GenerateCustomers(int start, int count)
{
List<Customer> list = new List<Customer>();
for(int i = start; i < start + count; i++)
{
list.Add(new Customer() { Name ="Customer_" + i});
}
return list;
}
public class EntityContext : DbContext
{
public EntityContext() : base(FiddleHelper.GetConnectionStringSqlServer())
{
}
public DbSet<Customer> Customers { get; set; }
}
public class Customer
{
public int CustomerID { get; set; }
public string Name { get; set; }
}
}