EFE - Temporary Table - TemporaryTableAppendSql (EF Core)

CSharp · Console

/Program.cs

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

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

/*
## 🏷️ TemporaryTableAppendSql

Appends a hardcoded SQL statement right after the temporary table is created.

This option is **mostly used when you want to keep the temporary table**, either by persisting it or by using it as a permanent table, and need to prepare it in advance (for example, by creating indexes).

When used, you can execute any SQL you want, such as creating a custom index on the table.

To have the temporary table name automatically replaced, you must use the `@(Model.TemporaryTableName)` placeholder in your SQL template.

### 💡 Why it can be useful

* **Permanent-like usage** → Prepare the table when you keep it alive after the operation.
* **Custom indexing** → Create indexes once for better performance in later queries.
* **Advanced scenarios** → Ideal when using `TemporaryTablePersist` or `UsePermanentTable`.
* **Debugging & inspection** → Makes analysis easier when you want to inspect or reuse the data.
*/

using System;
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())
		{
			// open the connection first to be able to access the temporary table data later
			context.Database.OpenConnection();
			
			// minimum 11 customers to use a temporary table
			var customers = GenerateCustomer(11);
			
			context.BulkMerge(customers, options =>
			{
				options.TemporaryTableAppendSql = "CREATE INDEX IX_CustomIndex ON @(Model.TemporaryTableName) (ZZZ_Index, IsActive);";
			});
			
			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 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; }
	}
}
;