Skip to content

Truncate Tables

Pawel Gerr edited this page Mar 4, 2026 · 7 revisions

Required Nuget Package:
Thinktecture.EntityFrameworkCore.SqlServer
Thinktecture.EntityFrameworkCore.PostgreSQL
Thinktecture.EntityFrameworkCore.Sqlite

Adds support for TRUNCATE TABLE.

Looking for conditional bulk delete? EF Core natively supports deleting entities matching a condition via ExecuteDeleteAsync(). TRUNCATE TABLE removes all rows from a table without conditions.

Configuration

Add support for truncating tables.

If you are using Lazy Loading then disable the registration of temp tables for primites types sqlOptions.AddBulkOperationSupport(configureTempTablesForPrimitiveTypes: false).

var services = new ServiceCollection()
                       .AddDbContext<DemoDbContext>(builder => builder
                               // SQL Server
                               .UseSqlServer("conn-string", sqlOptions =>
                                                            {
                                                                 sqlOptions.AddBulkOperationSupport();
                                                            })
                               // PostgreSQL
                               //.UseNpgsql("conn-string", npgsqlOptions =>
                               //                          {
                               //                                npgsqlOptions.AddBulkOperationSupport();
                               //                          })
                               // SQLite
                               //.UseSqlite("conn-string", sqliteOptions =>
                               //                          {
                               //                                sqliteOptions.AddBulkOperationSupport();
                               //                          })

Usage

await ctx.TruncateTableAsync<Customer>();

PostgreSQL: CASCADE

PostgreSQL does not allow truncating tables that have foreign key references from other tables unless CASCADE is specified. Use the cascade parameter to also truncate dependent tables.

await ctx.TruncateTableAsync<Customer>(cascade: true);

Clone this wiki locally