CSharp · Console
// Entity Framework Extensions
// Doc: https://entityframework-extensions.net/where-not-exists-bulk-insert
// @nuget: Microsoft.EntityFrameworkCore.SqlServer
// @nuget: Z.EntityFramework.Extensions.EFCore
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
using (var context = new EntityContext())
{
context.Database.EnsureCreated();
}
// Seed
using (var context = new EntityContext())
{
var customers = new List<Customer>();
customers.Add(new Customer() { Code = "A", Name = "Customer_A", TenantID = 1 });
customers.Add(new Customer() { Code = "B", Name = "Customer_B", TenantID = 1, IsSoftDeleted = true });
customers.Add(new Customer() { Code = "C", Name = "Customer_C", TenantID = 2 });
context.BulkInsert(customers);
FiddleHelper.WriteTable("1 - Customers Before", context.Customers.AsNoTracking());
}
// Match with a Custom Key and Formula
using (var context = new EntityContext())
{
var tenantID = 1;
var customers = new List<Customer>();
customers.Add(new Customer() { Code = "A", Name = "Customer_A", TenantID = tenantID });
customers.Add(new Customer() { Code = "B", Name = "Customer_B", TenantID = tenantID });
customers.Add(new Customer() { Code = "C", Name = "Customer_C", TenantID = tenantID });
context.Customers.Where(x => x.TenantID == tenantID).WhereNotExistsBulkInsert(customers, options => {
options.QueryFilterPrimaryKeyExpression = x => x.Code;
options.QueryFilterPrimaryKeyAndFormula = "IsSoftDeleted = 0";
});
// Customer_A are skipped because they already exist in TenantID = 1.
// Customer_B is inserted even though a matching customer exists in TenantID = 1, because the existing row does not satisfy the IsSoftDeleted = 0 condition.
// Customer_C is inserted because it does not exist in TenantID = 1.
FiddleHelper.WriteTable("2 - Customers After", context.Customers.AsNoTracking().ToList());
}
}
}
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
public class EntityContext : DbContext
{
public EntityContext()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()));
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Property(x => x.CustomerID).ValueGeneratedOnAdd();
modelBuilder.Entity<Customer>().HasKey(x => new { x.TenantID, x.CustomerID });
}
public DbSet<Customer> Customers { get; set; }
}
public class Customer
{
public int TenantID { get; set; }
public int CustomerID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public bool IsSoftDeleted { get; set; }
}