CSharp · Console
// Entity Framework Extensions
// Doc: https://entityframework-extensions.net/pre-bulk-delete
// @nuget: Microsoft.EntityFrameworkCore.SqlServer
// @nuget: Z.EntityFramework.Extensions.EFCore
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using Microsoft.Data.SqlClient;
using Z.EntityFramework.Extensions;
public class Program
{
public static void Main()
{
using (var context = new EntityContext())
{
context.Database.EnsureCreated();
}
GenerateData();
EntityFrameworkManager.PreBulkDelete = (ctx, obj) =>
{
var list = obj as IEnumerable<Customer>;
foreach (var customer in list)
{
customer.IsDeleted = true;
}
ctx.BulkUpdate(list);
((List<Customer>)obj).Clear();
};
using (var context = new EntityContext())
{
FiddleHelper.WriteTable("Before_BulkDelete", context.Customers.ToList());
var list = context.Customers.Take(2).ToList();
context.BulkDelete(list);
}
using (var context = new EntityContext())
{
FiddleHelper.WriteTable("After_BulkDelete", context.Customers.ToList());
}
}
public static void GenerateData()
{
using (var context = new EntityContext())
{
context.Customers.Add(new Customer() { Name ="Customer_A", IsDeleted = false });
context.Customers.Add(new Customer() { Name ="Customer_B", IsDeleted = false });
context.Customers.Add(new Customer() { Name ="Customer_C", IsDeleted = false });
context.Customers.Add(new Customer() { Name ="Customer_D", IsDeleted = false });
context.BulkSaveChanges();
}
}
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 Name { get; set; }
public string Description { get; set; }
public Boolean IsDeleted { get; set; }
}
}