Covers large-scale writes from .NET to SQL Server: SaveChanges batching and MaxBatchSize, chunked ExecuteUpdate, SqlBulkCopy into staging tables with MERGE, table-valued parameters, transaction log, lock escalation and how to benchmark them.
Pick by volume and shape. SaveChanges batches commands (the SQL Server provider defaults to 42 statements per batch) but still runs one statement per row and tracks every entity, so it is fine for thousands of rows, not millions. ExecuteUpdate/ExecuteDelete run one set-based statement with no tracking; for a million rows I chunk by key range so each transaction stays short. For 5 million inserts, SqlBulkCopy streams rows using the bulk-insert protocol, ideally into a staging table, followed by a set-based MERGE or UPDATE ... JOIN. Table-valued parameters suit thousands of rows sent into one statement. Batch size trades round trips against transaction log growth, lock escalation (about 5,000 locks) and Azure SQL log rate limits. I decide by measuring rows per second and log usage on production-sized data.
"The first thing I ask is how many rows and what shape: inserts, updates by a rule, or upserts from a file. EF Core's
SaveChangesis great for business transactions, but for millions of rows it's the wrong tool. It does batch, the SQL Server provider sends up to 42 statements per round trip by default, but each row is still its own INSERT or UPDATE, every entity sits in the change tracker, and DetectChanges gets slower as the tracker grows.For updates that follow a rule, like 'mark all orders older than 90 days as archived',
ExecuteUpdatesends one UPDATE statement and never loads the rows. At a million rows I still chunk it, say 10,000 to 50,000 rows per statement by primary key range, because one giant UPDATE holds locks, escalates to a table lock and fills the transaction log, and on Azure SQL log generation is rate-governed by the service tier. For the nightly 5 million row load, I useSqlBulkCopyinto a staging table. It uses the bulk insert protocol, so it reaches hundreds of thousands of rows per second, and the staging table keeps the live table untouched until a set-basedMERGEorUPDATE ... FROM ... JOINapplies the changes in chunks. For a few thousand rows from an API call, a table-valued parameter into one statement is a nice middle ground.For example, at [company] we had a nightly product feed of [about 4 million rows] that ran through
SaveChangesand took [over two hours]. I [moved it to SqlBulkCopy into a staging table and a chunked MERGE], and it dropped to [about 6 minutes]. The mistake I see is picking a batch size or a library from a blog post. I measure rows per second, log usage and blocking on a copy of production, because Azure SQL tier limits change the answer."
| Option | Rows | Mechanism | Tracks entities | Fires SaveChanges interceptors |
|---|---|---|---|---|
SaveChanges with AddRange |
Up to tens of thousands | One statement per row, batched (default 42 per round trip) | Yes | Yes |
ExecuteUpdate / ExecuteDelete |
Any, chunked | One set-based statement | No | No (command interceptors still see it) |
| Table-valued parameter | Thousands | One statement over a TVP | No | No |
SqlBulkCopy |
Hundreds of thousands to millions | TDS bulk insert stream | No | No |
| Third-party (e.g. EFCore.BulkExtensions) | Large | Wraps SqlBulkCopy and MERGE | Optional | No |
EFCore.BulkExtensions is dual-licensed: free under a community licence for organisations under US$1 million annual revenue, otherwise commercial. Check the licence before adopting it; an MIT fork exists.
| Smaller batches | Larger batches |
|---|---|
| More round trips | Fewer round trips |
| Short transactions, little blocking | Long transactions, lock escalation past ~5,000 locks |
| Log can truncate between batches | Large log use; Azure SQL log rate throttling |
| Easy restart from a checkpoint | Large rework on failure |
A nightly product feed [in a system I worked on] inserted and updated about 4 million rows through SaveChanges in 1,000-entity chunks and took over two hours, with the worker reaching 3 GB of memory. SqlBulkCopy into a heap staging table (about 90 seconds) followed by a MERGE in 50,000-row key ranges (about 4 minutes) brought the job to about 6 minutes and 200 MB of memory.
Checks that the candidate can pick the right write mechanism for the volume, understands the database-side costs (log, locks, Azure SQL governance), and measures instead of guessing.
Green flags
SaveChanges batches but is row-oriented and tracks entitiesExecuteUpdate and explains lock escalation and log growthSqlBulkCopy into staging with a set-based applyRed flags
SaveChanges per rowAddRange(10,000 entities) -> SaveChanges
DetectChanges over the tracker
-> batch 1: INSERT ...; INSERT ...; (up to MaxBatchSize = 42 statements, or a MERGE ... OUTPUT for generated keys)
-> batch 2: ...
-> ~240 round trips, one transaction
The SQL Server provider combines inserts for the same table, often using MERGE ... OUTPUT or INSERT ... OUTPUT to read generated keys back, but it is still row-oriented and every entity keeps a snapshot in memory. You can change the batch with UseSqlServer(cs, o => o.MaxBatchSize(100)); the default came from benchmarks, so measure before changing it.
UPDATE [o] SET [o].[Status] = 3
FROM [Orders] AS [o]
WHERE [o].[CreatedAt] < @cutoff AND [o].[Status] = 1 AND [o].[Id] > @from AND [o].[Id] <= @to
One statement updates every matching row server-side. Unchunked, a million-row UPDATE takes row or page locks until SQL Server escalates to a table lock (it tries at about 5,000 locks on one object), blocking every reader not using RCSI, and the whole change must fit in the log until it commits. Chunking by key range keeps each transaction small; on Azure SQL with accelerated database recovery and the full recovery model, the log can then be backed up and reused. EF Core 10 also lets ExecuteUpdate take a normal lambda for setters, which makes conditional setters easier to build.
SqlBulkCopy uses the TDS bulk load protocol: rows stream in large buffers without a statement per row. Key options: BatchSize (rows per commit), EnableStreaming with an IDataReader or IAsyncEnumerable source to avoid buffering everything, SqlBulkCopyOptions.TableLock for faster loads into an empty staging heap, and ColumnMappings. It inserts only; updates and upserts happen in SQL afterwards.
file / API -> IDataReader -> SqlBulkCopy -> staging heap -> MERGE in key ranges -> live table
A user-defined table type lets you send a DataTable or IEnumerable<SqlDataRecord> as one parameter and join it in a set-based statement. Good for thousands of rows per call; the parameter is materialised in tempdb, and very large TVPs are slower than bulk copy.
Azure SQL governs log generation rate per service tier, so a bulk load can be throttled no matter how fast the client is: waits show as LOG_RATE_GOVERNOR. Hyperscale and Business Critical have different limits. Scaling up for the load window or spreading work over time are both valid answers.
sys.dm_db_resource_stats for avg_log_write_percent and CPU during the load.sys.dm_tran_locks and blocked-process reports for escalation and blocking.AddRange + SaveChanges, then with SqlBulkCopy, and compare rows per second and peak memory.ExecuteUpdate with and without chunking while another session reads the table; watch sys.dm_tran_locks for escalation.MaxBatchSize to 10, 42 and 200 and benchmark a 20,000-row insert.SqlBulkCopy and write a chunked MERGE; check avg_log_write_percent in sys.dm_db_resource_stats.SqlBulkCopy.A nightly import: SqlBulkCopy into staging, then a chunked set-based apply; plus a chunked ExecuteUpdate for rule-based updates.
namespace Shop.Imports;
using System.Data;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
public sealed record ProductFeedRow(string Sku, string Name, decimal Price);
public sealed class ProductFeedImporter(ShopDbContext db, ILogger<ProductFeedImporter> logger)
{
public async Task ImportAsync(IAsyncEnumerable<ProductFeedRow> rows, CancellationToken ct)
{
var connection = (SqlConnection)db.Database.GetDbConnection();
await db.Database.OpenConnectionAsync(ct);
try
{
await db.Database.ExecuteSqlAsync($"TRUNCATE TABLE staging.ProductFeed", ct);
using var bulk = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, externalTransaction: null)
{
DestinationTableName = "staging.ProductFeed",
BatchSize = 50_000, // rows per commit: keeps log use bounded
EnableStreaming = true,
BulkCopyTimeout = 0
};
bulk.ColumnMappings.Add(nameof(ProductFeedRow.Sku), "Sku");
bulk.ColumnMappings.Add(nameof(ProductFeedRow.Name), "Name");
bulk.ColumnMappings.Add(nameof(ProductFeedRow.Price), "Price");
await bulk.WriteToServerAsync(await ToDataTableAsync(rows, ct), ct);
// Apply in key ranges so each transaction stays short and lock escalation is avoided.
var maxId = await db.Database.SqlQuery<int>($"SELECT ISNULL(MAX(Id), 0) AS [Value] FROM staging.ProductFeed").SingleAsync(ct);
for (var from = 0; from < maxId; from += 50_000)
{
var to = from + 50_000;
var affected = await db.Database.ExecuteSqlAsync($"EXEC dbo.ApplyProductFeedRange @From = {from}, @To = {to}", ct);
logger.LogInformation("Applied feed rows {From}-{To}: {Affected} changed", from, to, affected);
}
}
finally
{
await db.Database.CloseConnectionAsync();
}
}
// Kept simple for the example; for very large feeds implement an IDataReader over the stream instead.
private static async Task<DataTable> ToDataTableAsync(IAsyncEnumerable<ProductFeedRow> rows, CancellationToken ct)
{
var table = new DataTable();
table.Columns.Add("Sku", typeof(string));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Price", typeof(decimal));
await foreach (var r in rows.WithCancellation(ct)) table.Rows.Add(r.Sku, r.Name, r.Price);
return table;
}
}
public sealed class OrderArchiver(ShopDbContext db)
{
// Rule-based update without loading entities, chunked by primary key.
public async Task<int> ArchiveAsync(DateTime cutoff, CancellationToken ct)
{
var total = 0;
var maxId = await db.Orders.MaxAsync(o => (int?)o.Id, ct) ?? 0;
for (var from = 0; from < maxId; from += 20_000)
{
var to = from + 20_000;
total += await db.Orders
.Where(o => o.Id > from && o.Id <= to && o.CreatedAt < cutoff && o.Status == OrderStatus.Paid)
.ExecuteUpdateAsync(s => s.SetProperty(o => o.Status, OrderStatus.Archived), ct);
}
return total;
}
}
-- Applies one key range of the staging table (staging.ProductFeed has an IDENTITY Id).
CREATE OR ALTER PROCEDURE dbo.ApplyProductFeedRange @From int, @To int AS
BEGIN
SET NOCOUNT ON;
MERGE dbo.Products WITH (HOLDLOCK) AS t
USING (SELECT Sku, Name, Price FROM staging.ProductFeed WHERE Id > @From AND Id <= @To) AS s
ON t.Sku = s.Sku
WHEN MATCHED AND (t.Name <> s.Name OR t.Price <> s.Price) THEN
UPDATE SET t.Name = s.Name, t.Price = s.Price
WHEN NOT MATCHED BY TARGET THEN
INSERT (Sku, Name, Price) VALUES (s.Sku, s.Name, s.Price);
END
AddRange and one SaveChanges. Why it is wrong: one statement per row, a huge tracker and one enormous transaction. Instead: SqlBulkCopy into staging and a set-based apply.ExecuteUpdate over a million rows at peak time. Why it is wrong: lock escalation blocks readers and the log grows until commit. Instead: chunk by key range (start around 10,000 to 50,000 rows and tune by measurement; the right size depends on row width, indexes and the service tier) and run off-peak or with RCSI on.ExecuteUpdate and bulk copy bypass the change tracker. Why it is wrong: audit columns set in a SaveChangesInterceptor, concurrency tokens and in-memory entities are not updated, and no optimistic concurrency check happens. Instead: set audit columns explicitly in the statement (SetProperty(o => o.ModifiedAt, now)), add the expected RowVersion to the WHERE when a row-level check matters, and clear or reload tracked entities afterwards.SqlBulkCopy behaves like INSERT. Why it is wrong: by default it does not fire triggers and does not check CHECK or FOREIGN KEY constraints, which leaves constraints marked untrusted. Instead: set SqlBulkCopyOptions.FireTriggers and CheckConstraints when the target relies on them, or load a staging table without constraints and let the MERGE into the real table enforce them. Note that EF Core 7+ also needs HasTrigger(...) configured on tables with triggers, because its default OUTPUT clause fails on them.BatchSize set and no external transaction, each batch commits on its own, so a failure leaves a partial load. Instead: load staging, truncate and reload it on failure, apply to the live table in idempotent chunks, and record a checkpoint; wrap transient failures (Azure SQL errors such as 40613) in a retry around the whole chunk.MaxBatchSize to 1,000 because bigger seems faster. Why it is wrong: SQL Server has a 2,100 parameter limit per command and gains flatten quickly. Instead: benchmark a few values on real data.SqlBulkCopy code yourself.LOG_RATE_GOVERNOR waits) regardless of client speed. Instead: watch avg_log_write_percent in sys.dm_db_resource_stats or the Azure portal's Log IO percentage metric, chunk, and scale the tier for the window if needed.At scale the bottleneck moves from the .NET code to the database's log and locks, so the senior answer is about the shape of the work: stream rows in with bulk copy, transform set-based in SQL, commit in chunks, and make the job restartable from the last committed chunk. I keep EF Core for the business transactions around it and accept that bulk paths bypass interceptors, which means audit fields and domain events must be handled explicitly there.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
SaveChanges batching |
Business writes, up to tens of thousands of rows | Tracking memory, row-by-row SQL | Millions of rows |
Chunked ExecuteUpdate |
Rule-based updates or deletes | Bypasses tracking and SaveChanges interceptors | Per-row logic that needs domain code |
SqlBulkCopy + staging + MERGE |
Nightly loads, feeds, migrations | More SQL to maintain | Small, interactive writes |
| TVP | Thousands of rows from one request | User-defined type to version | Millions of rows |
I measure rows per second, avg_log_write_percent, blocking and worker memory on a production-sized copy, and I record the chosen batch size and why in the job's README or an ADR.
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.
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.
Make each chunk idempotent and record progress. Load into a staging table with a batch id, apply changes with a set-based MERGE keyed on the business key so re-running a chunk changes nothing, and write the last committed key range to a checkpoint table in the same transaction as the chunk. On restart, read the checkpoint and continue. Keep the import's input (file or snapshot) immutable so a re-run sees the same data.
How to tell it (STAR)
**S:** Our nightly supplier feed of about [4 million] products took over two hours and sometimes finished after stores opened, so prices were stale. **T:** I was asked to get it reliably under [30 minutes]. **A:** I measured first: dotnet-counters showed the worker's heap growing to 3 GB, and Azure SQL was saturating its log rate because EF Core sent row-by-row statements. I moved the load to SqlBulkCopy into a staging table, applied changes with a MERGE in 50,000-row ranges so each transaction was short, and added a checkpoint so a failure could resume. **R:** The job now runs in about [6 minutes] using around [200 MB], log waits disappeared, and we haven't missed the [5 am] deadline since.
Last updated 23 Nov 2026.