📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What are your options for bulk operations with EF Core? Explain ExecuteUpdate and ExecuteDelete, how SaveChanges batches AddRange, when you drop to SqlBulkCopy or a third-party library, and what skipping the change tracker means for interceptors, concurrency and in-memory state.

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).

Mid-Level Theory Intermediate bulk-operations ef-core executeupdate performance sql-server sqlbulkcopy

🎯 Key points

  • ExecuteUpdateAsync / ExecuteDeleteAsync (introduced in EF Core 7) send one set-based UPDATE/DELETE without loading entities; EF Core 10 added normal (non-expression) lambdas for the setters
  • They bypass the change tracker: tracked entities go stale, SaveChanges interceptors and soft-delete logic don't run, concurrency tokens aren't checked automatically
  • AddRange + SaveChanges batches commands (SQL Server MaxBatchSize default 42) and uses MERGE ... OUTPUT for generated keys; fine up to tens of thousands of rows
  • SqlBulkCopy streams rows with the TDS bulk protocol: fastest for 100k+ inserts, no generated-key fix-up, constraints and triggers off by default
  • Table-valued parameters or a staging table + MERGE for bulk upserts
  • Third-party libraries (EFCore.BulkExtensions, Entity Framework Extensions) wrap SqlBulkCopy; check current licence terms
  • Execute* run immediately and enlist in the current transaction: wrap multi-step bulk work in one transaction (inside the execution strategy) and chunk to limit log growth and lock escalation (~5,000 locks)
  • Measure rows/second, log generated, blocking and impact on concurrent traffic, not just wall time

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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, ExecuteUpdateAsync and ExecuteDeleteAsync translate a LINQ query straight into one set-based statement: UPDATE ... SET ... FROM ... WHERE .... EF Core 10 made ExecuteUpdate nicer 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 uses MERGE with OUTPUT to get identity values back. For a few thousand rows that's fine. For hundreds of thousands, I use SqlBulkCopy from 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 one MERGE or UPDATE plus INSERT, 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, SaveChanges interceptors don't run (so audit columns and soft delete silently don't happen), and concurrency tokens aren't checked unless I put them in the Where. The mistake I see is someone replacing a loop with ExecuteDeleteAsync on 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."


Options

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.

What bypassing the tracker means

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

Production example

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].

🔍 What the interviewer is checking

Checks the candidate can pick the right bulk mechanism and understands what is lost when bypassing the change tracker.

Green flags

  • Uses ExecuteUpdate/Delete for set-based work and knows SaveChanges batching.
  • Knows SqlBulkCopy and staging-table upserts, including constraint and trigger options.
  • Names the bypass consequences: stale tracker, interceptors, concurrency.
  • Mentions chunking, lock escalation and licensing.

Red flags

  • Loops over entities with SaveChanges per row.
  • Thinks ExecuteDelete respects soft-delete interceptors.
  • Has never measured bulk throughput.

📚 Learn in depth

1. ExecuteUpdate and ExecuteDelete

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.

2. How SaveChanges batches inserts

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.

3. SqlBulkCopy

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.

4. Upserts

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.

5. Locking and the log

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.

6. Third-party libraries

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.

Try it yourself

  1. Benchmark inserting 100k rows: per-row SaveChanges, one AddRange, and SqlBulkCopy.
  2. Change MaxBatchSize to 10, 42 and 200 and compare.
  3. Run ExecuteUpdateAsync while an entity is tracked and inspect the stale tracked value.
  4. Bulk copy with and without CheckConstraints and query sys.foreign_keys.is_not_trusted.
  5. Update 1M rows in one statement vs 50k chunks while watching sys.dm_tran_locks for escalation.

💻 Code

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
            }
        });
}

⚠ Common mistakes

  • Mistake: Loading thousands of entities to change one column. Why it is wrong: materialisation, snapshots and one UPDATE per row make it slow and memory-heavy. Instead: ExecuteUpdateAsync.
  • Mistake: Using 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.
  • Mistake: Continuing to use tracked entities after a bulk update. Why it is wrong: they hold stale values and a later SaveChanges can overwrite the bulk change. Instead: ChangeTracker.Clear() or a fresh context.
  • Mistake: One giant 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.
  • Mistake: 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.
  • Mistake: Updating millions of rows in one statement on a busy table. Why it is wrong: lock escalation blocks the table and the log balloons. Instead: chunk by key range.
  • Mistake: Adopting a bulk library without checking its licence. Why it is wrong: some popular ones require paid licences for commercial use. Instead: check terms, or use SqlBulkCopy directly.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions memory or DetectChanges with big imports. Why: Checks change tracker cost for large batches.
    How to answer

    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:

    • Chunk: save every few hundred to few thousand entities, then ChangeTracker.Clear() or use a new context per chunk.
    • Read with AsNoTracking() or projections.
    • Turn off AutoDetectChangesEnabled around bulk Add loops and call DetectChanges once.
    • For set-based changes, skip the tracker with 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.

  2. When: Candidate mentions ExecuteUpdate bypassing interceptors. Why: Checks what interceptors miss with bulk operations.
    How to answer

    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.

  3. When: Candidate mentions import jobs or ChangeTracker.Clear(). Why: Checks a real import job that slowed down and ran out of memory.
    How to answer

    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.

🛠 Real-world problems: how you handle them

ExecuteDelete hard-deleted soft-deletable customer notes
Situation
A [CRM] on Azure SQL where `CustomerNote` is soft-deletable through a `SaveChangesInterceptor`; deleted notes must be kept for [7 years] for compliance. A developer optimised a 'clear notes' feature from a loop to `ExecuteDeleteAsync`.
Signals
A support request to restore cleared notes found no rows with `IsDeleted = 1`; row counts in `CustomerNotes` dropped by [~18k] in a week; no errors.
Investigation
Diffed the release and found the `ExecuteDeleteAsync` change. Confirmed with `LogTo` that it issued `DELETE FROM [CustomerNotes] ...` and that the interceptor wasn't called. Checked Azure SQL point-in-time restore retention ([7 days] on the tier) to see what could be recovered.
Resolution
Immediately: restored the database to a point before the release under a new name, copied the deleted notes back with `IsDeleted = 1`, and reverted to `ExecuteUpdateAsync` setting `IsDeleted`, `DeletedAt` and `DeletedBy`. Then: added a Roslyn banned-API rule for `ExecuteDelete` on `ISoftDeletable` sets and moved the audit-column logic into a shared helper used by both paths.
Prevention
Integration test asserting 'clear notes' leaves rows with `IsDeleted = 1`; banned-API analyser; PR checklist item for any `Execute*` call; ADR documenting what bypasses `SaveChanges`.

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.

↩ Usually asked after

More in Advanced EF Core

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me