EF Extensions - SingleDelete - Delete Only When Additional Conditions Match

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;
			
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() { Status = 1, Name = "Customer_"  + i });
			}
			
			context.BulkInsert(customers);
		}
		
		// Delete Only When Additional Conditions Match
		using (var context = new EntityContext())
		{
			FiddleHelper.WriteTable("1 - Customers Before", context.Customers.AsNoTracking());
			
			for(int i = 0; i < customers.Count; i++)
			{
				customers[i].Status = i % 2;
			}
			
			FiddleHelper.WriteTable("2 - Customers Source", customers);
			
			foreach(var customer in customers)
			{
				// Using `DeleteMatchedAndConditionExpression`
				context.SingleDelete(customer, options => options.DeleteMatchedAndConditionExpression = x => x.Status);	

				// Using `DeleteMatchedAndConditionNames`
				// var matchedConditions = new List<string>() { nameof(Customer.Status) };
				// context.SingleDelete(customer, options => options.DeleteMatchedAndConditionNames = matchedConditions);
			}
			
			// Only customers with Status = 1 in the source has been deleted
			FiddleHelper.WriteTable("3 - 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 int Status { get; set; }
	public string Name { get; set; }
}
;