EFE - Temporary Table - TemporaryTableUseTableLock (EF Core)

CSharp · Console

/Program.cs

// Entity Framework Extensions
// Doc: https://entityframework-extensions.net/temporary-table#temporarytableusetablelock

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

/*
## 🏷️ TemporaryTableUseTableLock

Requests a **table-level lock** (`TABLOCK`) when inserting rows into the staging table (temporary or permanent).
This option is **`true` by default** because the staging table is created by the library for the bulk operation, so it is usually safe to lock it exclusively.

### 💡 Why it can be useful

* **Faster inserts on large loads** → Fewer lock acquisitions can significantly speed up bulk inserts.
* **Lower locking overhead** → Reduces the cost of row/page locks and avoids lock escalation.
* **More predictable performance** → A single table lock is often cheaper than many fine-grained locks during big batches.
* **Safe default** → Since the staging table is created exclusively for your operation, locking it won’t block other processes in most scenarios.

### ⚠️ Notes & gotchas

* **Blocks concurrent access**: If you override this option for a **global temp** or **permanent staging table** that may be shared across sessions, it can block other users.
* **Scope**: This option only affects inserts into the **staging table**. It does not affect locks on the **destination table** during the final merge/update step.
* **Tuning**: In rare cases with very high concurrency, you may set this option to `false` to reduce blocking — but performance may be slower.
*/

using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using Microsoft.Data.SqlClient;


public class Program
{
	public static void Main()
	{
		using (var context = new EntityContext())
		{
			context.Database.EnsureCreated();
		}
		
		using (var context = new EntityContext())
		{
			context.Customers.AddRange(AddToList());
			
			context.BulkSaveChanges(options =>
			{
				options.TemporaryTableUseTableLock = true;
			});
		}
		
		using (var context = new EntityContext())
		{
			FiddleHelper.WriteTable(context.Customers.Take(5).ToList());	
		}
	}
		 	
	public static List<Customer> AddToList()
	{
		var list = new List<Customer>();
		for (int i = 0; i < 1000; i++)
		{
			list.Add(new Customer() { Name ="Customer_" + i});
		}
		
		return list;
	}

	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 Boolean IsActive { get; set; }
	}
}
;