EF Extensions - SingleDelete - Delete Multiple Entities for Free

CSharp · Console

/Program.cs

// Entity Framework Extensions
// Doc: https://entityframework-extensions.net/bulk-delete

// @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();
		}
		
		var customers = new List<Customer>();
		
		// Seed
		using (var context = new EntityContext())
		{
			for(int i = 0; i < 5; i++)
			{
				customers.Add(new Customer() { Code = i.ToString(), Name = "Customer_"  + i });
			}
			
			context.BulkInsert(customers);
		}
		
		// Delete Multiple Entities for Free
		using (var context = new EntityContext())
		{
			customers = customers.Take(3).ToList();
			
			FiddleHelper.WriteTable("1 - Customers Before", context.Customers.AsNoTracking());
			
			foreach(var customer in customers)
			{
				context.SingleDelete(customer);
			}			

			FiddleHelper.WriteTable("2 - Customers After", context.Customers.AsNoTracking());
		}	
	}
}

/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);
	}

	public DbSet<Customer> Customers { get; set; }
}

public class Customer
{
	public int CustomerID { get; set; }
	public string Code { get; set; }
	public string Name { get; set; }
}
;