EF Plus - ExecuteDelete + QueryHint

CSharp · Console

/Program.cs

// Entity Framework Extensions
// Doc: https://entityframework-plus.net/execute-delete

// @nuget: Microsoft.EntityFrameworkCore.SqlServer
// @nuget: Z.EntityFramework.Plus.EFCore

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Z.EntityFramework.Plus;

public class Program
{
	public static async Task 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 < 50; i++)
			{
				customers.Add(new Customer() { Name = "Customer_"  + i, Code = (i % 3).ToString() });
			}
			
			await context.BulkInsertAsync(customers);
		}
		
		// Example
		using (var context = new EntityContext())
		{
			var rowsAffected = await context.Customers.WithHint(SqlServerTableHintFlags.TABLOCK).ExecuteDeleteAsync();
			
			Console.WriteLine("---");
			Console.WriteLine("RowsAffected:" + rowsAffected);
		}	
	}
}

/EntityContext.cs

using System.Data.Common;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using System;
using System.Threading;
using System.Threading.Tasks;

public class EntityContext : DbContext
{
	public EntityContext()
	{
	}
	
	protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
	{
		optionsBuilder.UseSqlServer(new SqlConnection(FiddleHelper.GetConnectionStringSqlServer())).AddInterceptors(new MyCommandInterceptor());

		base.OnConfiguring(optionsBuilder);
	}

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

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

public class MyCommandInterceptor : DbCommandInterceptor
{
    public override ValueTask<int> NonQueryExecutedAsync(DbCommand command, CommandExecutedEventData eventData, int result, CancellationToken cancellationToken = default)
    {
        Console.WriteLine(command.CommandText);

        return new ValueTask<int>(result);
    }
}
;