CSharp · Console
// Entity Framework Classic
// Doc: https://entityframework-classic.net/bulk-insert
// @nuget: Z.EntityFramework.Classic
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Data.Entity;
public class Program
{
public static void Main()
{
GenerateCustomers();
using (var context = new EntityContext())
{
FiddleHelper.WriteTable("1 - Customers Before", context.Customers);
var customers = new List<Customer>();
customers.Add(new Customer() { Code = "ExistingCode_0", Name = "ZZZ" });
customers.Add(new Customer() { Code = "NonExistingCode", Name = "Projects" });
context.BulkInsert(customers, options => {
options.InsertIfNotExists = true;
options.ColumnPrimaryKeyExpression = x => new { x.Code };
});
FiddleHelper.WriteTable("2 - Customers After", context.Customers);
}
}
public static void GenerateCustomers()
{
using (var context = new EntityContext())
{
var customers = new List<Customer>();
customers.Add(new Customer() { Code = "ExistingCode_0", Name = "ExistingName_0" });
customers.Add(new Customer() { Code = "ExistingCode_1", Name = "ExistingName_1" });
context.BulkInsert(customers);
}
}
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 Code { get; set; }
public string Name { get; set; }
}
}