CSharp · Console
// Entity Framework Extensions
// Doc: https://entityframework-extensions.net/temporary-table#temporarytableschemaname
// @nuget: Microsoft.EntityFrameworkCore.SqlServer
// @nuget: Z.EntityFramework.Extensions.EFCore
/*
## 🏷️ TemporaryTableSchemaName
Gets or sets the schema name to use for the staging table.
⚠️ When using a **temporary table** (local `#` or global `##`), the schema name is always ignored due to **SQL Server limitations**.
This option should only be used when working with **permanent tables**.
👉 If you set a schema name while using a temporary table, it will simply be **ignored** without causing an error.
### 💡 Why it can be useful
* Organize staging tables under a dedicated schema (e.g., `"Staging"` or `"Temp"`) instead of cluttering the `dbo` schema.
* Apply different **permissions or security rules** depending on the schema.
* Keep staging tables **isolated from production objects**, making maintenance and cleanup easier.
*/
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.TemporaryTableSchemaName = "ZZZ";
options.TemporaryTableName = "MyTemporaryTableName"; // use a permanent table
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; }
}
[Table("MyTable", Schema = "ZZZ")]
public class Customer
{
public int CustomerID { get; set; }
public string Name { get; set; }
public Boolean IsActive { get; set; }
}
}