EFE - Temporary Table - TemporaryTableCreateAndDrop (EF Core)

CSharp · Console

/Program.cs

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

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

/*
## 🏷️ TemporaryTableCreateAndDrop

Forces the library to explicitly `CREATE` the temporary table and then automatically `DROP` it after the operation is complete.

This option is a shortcut that combines `TemporaryTableCreate = true;` with automatic cleanup, so you don’t need to manage dropping the table yourself.

When the `TemporaryTableName` is automatically generated by the library, the table is already created and dropped for you — so you don’t need to set this option.

### 💡 Why it can be useful

* **One-step setup** → Automatically creates and cleans up the staging table with a single option.
* **Keeps your database clean** → Prevents leftover temporary or staging tables from piling up.
* **Great for testing** → Ensures each test run starts fresh without manual cleanup.
* **Reduces mistakes** → No need to remember to drop the table later.
*/

using System;
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.TemporaryTableName = "#MyTemporaryTableName";
				options.TemporaryTableCreateAndDrop = 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; }
	}
}
;