Covers bulk data changes with EF Core 10: set-based ExecuteUpdateAsync/ExecuteDeleteAsync (EF Core 7+, delegate setters in EF Core 10), SaveChanges batching and MaxBatchSize for AddRange, SqlBulkCopy and table-valued parameters, third-party libraries and their licensing, and the consequences of bypassing the change tracker (stale tracked entities, no SaveChanges interceptors, no automatic concurrency checks, cascade and trigger behaviour).
For set-based changes use ExecuteUpdateAsync/ExecuteDeleteAsync (EF Core 7+): one UPDATE/DELETE statement, no entities loaded, and in EF Core 10 the setters can be a normal lambda. For inserts, AddRange + SaveChanges already batches commands (default 42 statements per batch on SQL Server) with MERGE ... OUTPUT for keys, which is fine up to tens of thousands of rows. Beyond that, SqlBulkCopy streams rows with the bulk-load protocol and is an order of magnitude faster; for upserts use a staging table + MERGE or a table-valued parameter. Third-party libraries wrap these, but check their licences. Skipping the change tracker has costs: tracked entities go stale, SaveChanges interceptors (audit, soft delete) don't run, and concurrency tokens aren't checked. The trade-off is raw speed versus the safety nets EF normally gives you.
"I split bulk work into updates and deletes versus inserts. For updates and deletes, the change tracker is the wrong tool: loading 200,000 entities to flip a flag means 200,000 materialisations, snapshots and an UPDATE per row. Since EF Core 7,
ExecuteUpdateAsyncandExecuteDeleteAsynctranslate a LINQ query straight into one set-based statement:UPDATE ... SET ... FROM ... WHERE .... EF Core 10 madeExecuteUpdatenicer by accepting a regular lambda, so I can add setters conditionally without building expression trees.For inserts, people underestimate plain
SaveChanges. It batches: on SQL Server it sends up to 42 statements per round trip by default and usesMERGEwithOUTPUTto get identity values back. For a few thousand rows that's fine. For hundreds of thousands, I useSqlBulkCopyfrom Microsoft.Data.SqlClient, which uses the TDS bulk-load protocol, minimal logging when conditions allow, and does a million narrow rows in seconds. It doesn't give me generated keys back, and by default it doesn't check constraints or fire triggers, so I opt in where needed. For upserts, I bulk copy into a staging table and run oneMERGEorUPDATEplusINSERT, or pass a table-valued parameter. Libraries like EFCore.BulkExtensions wrap this nicely, but licensing has changed in recent years, so I check terms before adopting one.The important part is what you lose. These paths skip the change tracker, so entities already tracked in the context are now stale,
SaveChangesinterceptors don't run (so audit columns and soft delete silently don't happen), and concurrency tokens aren't checked unless I put them in theWhere. The mistake I see is someone replacing a loop withExecuteDeleteAsyncon a soft-deletable table and hard-deleting customer data. Bulk APIs are fast because they skip the safety nets, so I add those back deliberately."
| Approach | Best for | Rough throughput* | Keys back | Interceptors / tracker |
|---|---|---|---|---|
Loop + SaveChanges per row |
Never for bulk | ~hundreds rows/s | Yes | Yes |
AddRange + one SaveChanges |
Up to ~10-50k inserts | ~5-20k rows/s | Yes | Yes |
ExecuteUpdate / ExecuteDelete |
Set-based changes | Engine speed | n/a | No |
SqlBulkCopy |
100k+ inserts, loads | ~100k-1M rows/s | No | No |
Staging table + MERGE / TVP |
Bulk upserts | High | Via OUTPUT | No |
*Indicative only: depends on row width, indexes, tier and network. Measure on your data.
| Concern | Consequence | What to do |
|---|---|---|
| Tracked entities | Hold old values | ChangeTracker.Clear() or use a fresh context |
| SaveChanges interceptors | Not called | Set audit columns in the setter; ban ExecuteDelete on soft-delete sets |
| Concurrency tokens | Not checked | Put the version in Where, check rows affected |
| Cascade delete | Database cascades only (EF's client-side cascade doesn't run) | Configure ON DELETE CASCADE or delete children first |
| Global query filters | Still applied to ExecuteUpdate/Delete |
Be aware when ignoring them |
A nightly price import of [1.2M] rows went from [~45 min] with SaveChanges per batch to [~70 s] using SqlBulkCopy into a staging table plus one MERGE, run in chunks of [100k] to keep the transaction log on Azure SQL under [2 GB].
Checks the candidate can pick the right bulk mechanism and understands what is lost when bypassing the change tracker.
Green flags
ExecuteUpdate/Delete for set-based work and knows SaveChanges batching.SqlBulkCopy and staging-table upserts, including constraint and trigger options.Red flags
SaveChanges per row.ExecuteDelete respects soft-delete interceptors.await db.Customers
.Where(c => c.LastOrderAt < cutoff && c.Status == Status.Active)
.ExecuteUpdateAsync(s => s
.SetProperty(c => c.Status, Status.Dormant)
.SetProperty(c => c.ModifiedAt, now), ct);
UPDATE [c]
SET [c].[Status] = 2, [c].[ModifiedAt] = @__now_1
FROM [Customers] AS [c]
WHERE [c].[LastOrderAt] < @__cutoff_0 AND [c].[Status] = 1
In EF Core 10 the setter argument is an Action<UpdateSettersBuilder<T>>, so you can write:
await q.ExecuteUpdateAsync(s =>
{
s.SetProperty(c => c.Status, Status.Dormant);
if (stampAudit) s.SetProperty(c => c.ModifiedAt, now);
}, ct);
It returns the number of rows affected. It runs immediately (not deferred to SaveChanges) and enlists in any current transaction.
AddRange(10_000 entities) -> SaveChanges
batches of up to MaxBatchSize (42 by default on SQL Server) statements per round trip
inserts with generated keys -> MERGE ... USING (VALUES ...) OUTPUT INSERTED.Id
10,000 rows ~ 240 round trips, inside one transaction
Tune with UseSqlServer(cs, o => o.MaxBatchSize(100)), but measure: larger batches aren't always faster. The other big cost is the change tracker itself: 100k tracked entities use a lot of memory and slow DetectChanges, so chunk and ChangeTracker.Clear() between chunks.
client --TDS bulk load (INSERT BULK)--> SQL Server
streams rows, no per-row statements
options: TableLock (enables minimal logging on heaps/empty tables), CheckConstraints, FireTriggers, KeepIdentity
BatchSize: rows per internal batch; EnableStreaming for IDataReader sources
Defaults matter: without CheckConstraints, foreign keys and check constraints aren't validated and are marked not trusted, which can hurt query plans later. Without FireTriggers, triggers don't run.
1. CREATE TABLE #staging (...) -- or a permanent staging table
2. SqlBulkCopy -> #staging
3. MERGE target USING #staging ON key
WHEN MATCHED THEN UPDATE ...
WHEN NOT MATCHED THEN INSERT ...;
The temp table must live on the same open connection; with EF, open db.Database.GetDbConnection() yourself and keep it open. Many teams avoid MERGE because of its history of bugs and concurrency surprises and use UPDATE ... FROM + INSERT ... WHERE NOT EXISTS with HOLDLOCK instead.
SQL Server escalates row locks to a table lock at about 5,000 locks on one object, so a 1M-row UPDATE can block the whole table. Chunk with a TOP (n) loop or by key range; on Azure SQL, large single transactions also grow the log and can hit log-rate governance limits.
EFCore.BulkExtensions and Entity Framework Extensions add BulkInsert, BulkUpdate, BulkMerge on top of SqlBulkCopy and staging tables, with key fix-up. EFCore.BulkExtensions moved to a dual licence a few years ago (free only under certain conditions); Entity Framework Extensions is commercial. Check the current terms with your legal or procurement team before adopting either.
SaveChanges, one AddRange, and SqlBulkCopy.MaxBatchSize to 10, 42 and 200 and compare.ExecuteUpdateAsync while an entity is tracked and inspect the stale tracked value.CheckConstraints and query sys.foreign_keys.is_not_trusted.sys.dm_tran_locks for escalation.Set-based update, batched insert and a transactional SqlBulkCopy upsert, each with the safety nets added back.
namespace Catalogue.Import;
using System.Data;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
public sealed record PriceRow(string Sku, decimal Price);
public sealed class PriceImport(CatalogueDbContext db, TimeProvider clock)
{
// 1. Set-based: no entities loaded. Audit columns set explicitly because interceptors won't run.
public Task<int> DiscontinueStaleAsync(DateTimeOffset cutoff, CancellationToken ct)
{
var now = clock.GetUtcNow();
return db.Products
.Where(p => p.LastSoldAt < cutoff && p.IsActive)
.ExecuteUpdateAsync(s =>
{
s.SetProperty(p => p.IsActive, false);
s.SetProperty(p => p.ModifiedAt, now); // EF Core 10: normal lambda, statements allowed
}, ct);
}
// 2. Medium inserts: SaveChanges batching, chunked so the tracker stays small.
public async Task AddAsync(IEnumerable<Product> products, CancellationToken ct)
{
foreach (var chunk in products.Chunk(5_000))
{
db.Products.AddRange(chunk);
await db.SaveChangesAsync(ct);
db.ChangeTracker.Clear(); // keep memory and DetectChanges flat
}
}
// 3. Large upsert: bulk copy into a staging table and apply it in ONE transaction,
// retried as a unit by the execution strategy. Safe to retry: the UPDATE is idempotent.
public Task UpsertPricesAsync(IReadOnlyList<PriceRow> rows, CancellationToken ct) =>
db.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
{
await db.Database.OpenConnectionAsync(ct); // one connection so #Prices survives
try
{
await using var tx = await db.Database.BeginTransactionAsync(ct);
var conn = (SqlConnection)db.Database.GetDbConnection();
var sqlTx = (SqlTransaction)tx.GetDbTransaction();
await db.Database.ExecuteSqlRawAsync(
"CREATE TABLE #Prices (Sku nvarchar(32) PRIMARY KEY, Price decimal(18,2) NOT NULL);", ct);
var table = new DataTable();
table.Columns.Add("Sku", typeof(string));
table.Columns.Add("Price", typeof(decimal));
foreach (var r in rows) table.Rows.Add(r.Sku, r.Price);
// SqlBulkCopy must use the same transaction, or SQL Server rejects it.
using var bulk = new SqlBulkCopy(conn, SqlBulkCopyOptions.CheckConstraints, sqlTx)
{
DestinationTableName = "#Prices",
BatchSize = 10_000
};
await bulk.WriteToServerAsync(table, ct);
await db.Database.ExecuteSqlAsync($"""
UPDATE p SET p.Price = s.Price, p.ModifiedAt = SYSUTCDATETIME()
FROM dbo.Products p JOIN #Prices s ON s.Sku = p.Sku
WHERE p.Price <> s.Price;
""", ct);
await tx.CommitAsync(ct); // any exception above disposes tx -> rollback
}
finally
{
await db.Database.CloseConnectionAsync(); // drops #Prices
}
});
}
ExecuteUpdateAsync.ExecuteDeleteAsync on an entity that relies on a soft-delete interceptor. Why it is wrong: it bypasses SaveChanges, so rows are hard-deleted. Instead: ExecuteUpdateAsync setting IsDeleted, or ban ExecuteDelete there.SaveChanges can overwrite the bulk change. Instead: ChangeTracker.Clear() or a fresh context.AddRange of 1M entities. Why it is wrong: the tracker uses gigabytes and DetectChanges slows to a crawl. Instead: chunk and clear, or use SqlBulkCopy.SqlBulkCopy with default options into tables with foreign keys. Why it is wrong: constraints aren't checked, become untrusted, and the optimiser loses join elimination. Instead: SqlBulkCopyOptions.CheckConstraints or re-validate with ALTER TABLE ... WITH CHECK CHECK CONSTRAINT.SqlBulkCopy directly.Bulk operations are where EF Core's abstractions stop helping, so I make the trade explicit: anything that bypasses SaveChanges gets a comment and a test proving audit, soft delete and concurrency still behave. I keep bulk code in a small number of import or maintenance classes rather than scattered ExecuteDelete calls in handlers.
The choice is driven by measurements: rows per second, transaction log generated (sys.dm_db_log_stats), blocking and lock escalation on the target table, and the effect on concurrent user traffic. On Azure SQL, log-rate governance is often the real ceiling, so chunking and off-peak scheduling matter as much as the API choice.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
ExecuteUpdate/Delete |
Set-based changes | Skips tracker and interceptors | Domain logic per entity |
Batched SaveChanges |
Up to tens of thousands of rows | Tracker memory | 100k+ rows |
SqlBulkCopy (+ staging) |
Large loads and upserts | Code, no key fix-up, constraint options | Small writes |
| Third-party bulk library | Many bulk paths, key fix-up wanted | Licence, dependency | Occasional use |
Every tracked entity costs an entry, an identity-map slot and an original-values snapshot, and DetectChanges scans all of them on every SaveChanges (and on Entries()/Entry()). On one long-lived context the tracked set keeps growing, so each save gets slower and the total becomes roughly quadratic, while memory climbs until the job runs out.
The fixes:
ChangeTracker.Clear() or use a new context per chunk.AsNoTracking() or projections.AutoDetectChangesEnabled around bulk Add loops and call DetectChanges once.ExecuteUpdate/ExecuteDelete, or SqlBulkCopy for millions of inserts.The trade-off: chunking gives up all-or-nothing atomicity, and bypassing the tracker skips interceptors and domain logic.
Interceptors let you run code before and after EF Core operations without touching every call site. The main ones are DbCommandInterceptor (see or change the SQL, time it, or suppress execution and return a cached result), SaveChangesInterceptor (inspect the ChangeTracker in SavingChangesAsync to set audit columns, turn deletes into soft deletes or write outbox rows), and DbConnectionInterceptor (run code as a connection opens, such as setting SESSION_CONTEXT for row-level security). You register them with AddInterceptors, usually resolved from DI. With AddDbContextPool they behave like singletons, so they must not capture scoped services. They don't see everything: ExecuteUpdate/ExecuteDelete bypass SaveChanges interceptors. The trade-off is central, invisible behaviour versus surprise for anyone reading a handler, so keep them few, fast and documented.
A steady climb from every restart means something is accumulating. In a worker the usual culprit is a DbContext created once (in the constructor or at the top of ExecuteAsync) and used for every message. The change tracker never forgets: each message adds entities, DetectChanges gets slower on every save, memory grows into gen 2, and the identity map returns already-tracked instances with their old values, which explains the stale data.
I'd confirm with dotnet-counters (GC heap, gen 2, EF active-db-contexts stuck at 1), a dotnet-gcdump full of InternalEntityEntry, and Application Insights showing SaveChanges duration rising. Mitigate with restarts or ChangeTracker.Clear(), then fix properly: a new context per message via IServiceScopeFactory.CreateAsyncScope() or IDbContextFactory<T>. The trade-off is negligible: contexts are cheap to create; long-lived ones are not.
How to tell it (STAR)
**S:** At [company], support couldn't restore a customer's cleared notes in our [CRM], even though notes were meant to be soft-deleted for [seven years]. **T:** I had to find out where they'd gone and recover them. **A:** A recent optimisation had replaced a loop with `ExecuteDeleteAsync`, which issues a real DELETE and never calls the SaveChanges interceptor that did our soft delete. I restored the database to a point before the release under a new name, copied [~18k] notes back as soft-deleted, switched the code to `ExecuteUpdateAsync` setting the delete flags, and added an analyser rule banning `ExecuteDelete` on soft-deletable entities. **R:** Every note was recovered, the feature was still [~40x] faster than the old loop, and the analyser has blocked [N] similar changes since.
Last updated 23 Nov 2026.