EF Extensions - WhereNotExistsBulkInsert

CSharp · Console

/Program.cs

// 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() { CustomerID = 1, Code = "A", Name = "Customer_A", TenantID = 1 });
			customers.Add(new Customer() { CustomerID = 2, Code = "B", Name = "Customer_B", TenantID = 1 });
			customers.Add(new Customer() { CustomerID = 3, Code = "C", Name = "Customer_C", TenantID = 2 });	
		
			context.BulkInsert(customers);
		
			FiddleHelper.WriteTable("1 - Customers Before", context.Customers.AsNoTracking());
		}
		
		// Example
		using (var context = new EntityContext())
		{
			var tenantID = 1;
			
			var customers = new List<Customer>();
			
			customers.Add(new Customer() { CustomerID = 1, Code = "A", Name = "Customer_A", TenantID = tenantID });
			customers.Add(new Customer() { CustomerID = 2, Code = "B", Name = "Customer_B", TenantID = tenantID });
			customers.Add(new Customer() { CustomerID = 3, Code = "C", Name = "Customer_C", TenantID = tenantID });
			
			context.Customers.Where(x => x.TenantID == tenantID).WhereNotExistsBulkInsert(customers);
						
			// Customer_A and Customer_B are skipped because they already exist in TenantID = 1.
			// Customer_C is inserted because it does not exist in TenantID = 1.
			FiddleHelper.WriteTable("2 - Customers After", context.Customers.AsNoTracking().ToList());
		}	
	}
}

/EntityContext.cs

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).ValueGeneratedNever();
        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; }
}
;