CSharp · Console
// Entity Framework Extensions
// Doc: https://entityframework-extensions.net/temporary-table#resolvedtemporarytablename
// @nuget: Microsoft.EntityFrameworkCore.SqlServer
// @nuget: Z.EntityFramework.Extensions.EFCore
/*
## 🏷️ ResolvedTemporaryTableName
Gets the final temporary table name used during the operation (whether it was automatically generated or explicitly provided).
This option is especially useful when combined with [`TemporaryTablePersist`](#temporarytablepersist), since the temporary table remains available after the operation and you may want to query it directly.
### 💡 Why it can be useful
* **Debugging** → Know exactly which table was created during the operation.
* **Custom queries** → When using `TemporaryTablePersist`, you can run queries directly on the temporary table.
* **Future operations** → Reuse the persisted temporary table data for later queries or other bulk operations.
* **Logging & monitoring** → Capture the resolved name for auditing or troubleshooting.
*/
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);
string temporaryTableName = "";
context.BulkMerge(customers, options =>
{
options.TemporaryTablePersist = true;
options.BulkOperationExecuted = op =>
{
// Capture the resolved temporary table name after execution
temporaryTableName = op.ResolvedTemporaryTableName;
};
});
Console.WriteLine($"Temporary table created: {temporaryTableName}");
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; }
}
}