EFE - Temporary Table - TemporaryTableUseSameName (EF Core)

CSharp · Console

/Program.cs

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

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

/*
## 🏷️ TemporaryTableUseSameName

Reuses the same temporary table name instead of generating a unique one.

When enabled, the library automatically builds the temporary table name using the prefix #ZZZ_, followed by the action suffix (insert, update, delete, merge, synchronize), and completed with your destination table name.

For example:

* Destination table: `Customer` → Temporary table: `#ZZZ_merge_Customer`

### 💡 Why it can be useful

* **Consistent table naming** → Makes debugging easier since you always know what temporary table to look for.
* **Query plan reuse** → SQL Server can cache and reuse execution plans more efficiently when the table name stays the same.
* **Better troubleshooting** → Helpful if you need to capture or inspect intermediate data during bulk operations.
*/

using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
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();
			CacheSchemaToIgnoreInLog(context);
		}
		
		using (var context = new EntityContext())
		{
			// minimum 11 customers to use a temporary table
			var customers = GenerateCustomer(11);
			
			StringBuilder sb = new StringBuilder();
			
			context.BulkMerge(customers, options =>
			{			
				options.TemporaryTableUseSameName = true;
				
				options.Log = s => sb.AppendLine(s);
			});
			
			Console.WriteLine(sb.ToString());
			
			FiddleHelper.WriteTable(context.Customers.AsNoTracking());
		}
	}
		 	
	public static List<Customer> GenerateCustomer(int max)
	{
		var list = new List<Customer>();
		for (int i = 0; i < max; i++)
		{
			list.Add(new Customer() { Name ="Customer_" + i});
		}
		
		return list;
	}
	
	public static void CacheSchemaToIgnoreInLog(EntityContext context)
	{
		var customers = GenerateCustomer(11);

		context.BulkInsert(customers, options => { options.IsReadOnly = true; });
	}

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