Skip to content

Bulk Insert with EF Core 10 — Handle Millions of Records

EF Core 10 has no bulk insert API. Learn when a tuned SaveChanges loop is enough, and when to use SqlBulkCopy, PostgreSQL COPY or a library for millions of rows.

Isaiah Clifford Opoku
Isaiah Clifford OpokuSoftware Engineer & ArchitectNovember 23, 2026·17 min read

Inserting a few hundred rows with EF Core is easy: AddRange, SaveChangesAsync, done. Then one day you need to import a 2-million-row CSV, seed a reporting table, or sync a nightly feed from a partner, and the same code that worked fine in development takes forty minutes, eats 6 GB of memory, or times out halfway through.

This post explains why EF Core’s normal save path struggles with large volumes, and then walks through the options from “a few small changes to your EF code” to “bypass EF entirely and stream rows straight into the database”. At each step you’ll see the code, what it costs, and when it’s the right choice.

Short version: EF Core 10 has no built-in bulk-copy API, and EF Core 11 doesn’t add one for relational databases either (its new bulk execution is for Azure Cosmos DB only). For tens of thousands of rows, a tuned SaveChanges loop is fine. For hundreds of thousands to millions, use your database’s native bulk-load mechanism, such as SqlBulkCopy on SQL Server or COPY on PostgreSQL, or a library that wraps it.

Versions used: .NET 10, EF Core 10.0.15, Npgsql.EntityFrameworkCore.PostgreSQL 10.0.4, EFCore.BulkExtensions 10.0.1 and linq2db.EntityFrameworkCore 10.8.0. Every snippet below comes from a demo project with tests that run against real SQL Server 2022 and PostgreSQL 17 databases. Get the full code on GitHub and run it yourself with dotnet test.

Why SaveChanges is slow for large inserts

SaveChangesAsync is optimized for the typical web request: load a few entities, change them, save. For that it’s excellent. But look at what it does for each entity you add:

  1. Change tracking. Every added entity gets a tracking entry with a snapshot of its values. A million entities means a million tracking entries in memory.
  2. Change detection. Before saving, DetectChanges walks through every tracked entity to see what changed. The more entities you track, the slower every call gets.
  3. One INSERT per row. EF batches statements to reduce round trips, but each row is still its own INSERT the database has to execute. By default, the SQL Server provider batches up to 42 statements per round trip, so a million rows is still roughly 24,000 round trips.
  4. Reading generated values back. If your key is a database identity column, EF has to get each new ID back from the database so it can set it on your object. That makes the generated SQL heavier than a plain insert.
%%{init: {"flowchart": {"wrappingWidth": 280}}}%%
flowchart TD
    A["AddRange: 1M products"] --> B["Tracker snapshots each one"]
    B --> C["DetectChanges scans them all"]
    C --> D["One INSERT per row, 42 per trip"]
    D --> E["Database returns each Id"]
    E --> F["EF sets each Id"]
    F --> G["About 24,000 round trips"]

Every step in that chain runs once per row. The bulk options later in this post remove most of them.

None of that is a flaw. It’s what gives you navigation fix-up, generated keys on your objects, and concurrency checks. You just don’t need any of it when you’re dumping a million rows from a file into a table.

The example

We’ll import products from a supplier feed:

public class Product
{
    public int Id { get; set; }
    public string Sku { get; set; } = string.Empty;
    public string Name { get; set; } = string.Empty;
    public decimal Price { get; set; }
    public int Stock { get; set; }
    public DateTime ImportedAtUtc { get; set; }
}

And assume we have a source that yields rows one at a time, so we never hold the whole file in memory:

IAsyncEnumerable<Product> ReadProductsAsync(string csvPath, CancellationToken ct);

Level 0: what not to do

// ❌ One SaveChanges per row: one round trip, one transaction, per product
await foreach (var product in ReadProductsAsync(path, ct))
{
    db.Products.Add(product);
    await db.SaveChangesAsync(ct);
}

This is the slowest possible approach: a database round trip and a separate transaction for every row. It’s surprisingly common in import jobs that started as “just a quick script”.

// ❌ Everything in one SaveChanges: one giant change tracker
var all = await ReadProductsAsync(path, ct).ToListAsync(ct);
db.Products.AddRange(all);
await db.SaveChangesAsync(ct);

This one looks efficient, but now EF tracks a million entities at once. Memory climbs into gigabytes, DetectChanges gets slower and slower, and if anything fails at row 999,000 the whole transaction rolls back and you start over.

Level 1: tune SaveChanges (fine up to tens of thousands of rows)

If your volume is modest, say up to around 50,000 rows, you can stay entirely within EF Core. The fix is to save in chunks and clear the change tracker between them, so memory stays flat:

public async Task ImportWithEfAsync(string path, CancellationToken ct)
{
    const int chunkSize = 2_000;
    var buffer = new List<Product>(chunkSize);

    db.ChangeTracker.AutoDetectChangesEnabled = false;

    await foreach (var product in ReadProductsAsync(path, ct))
    {
        buffer.Add(product);

        if (buffer.Count == chunkSize)
        {
            await SaveChunkAsync(buffer, ct);
            buffer.Clear();
        }
    }

    if (buffer.Count > 0)
        await SaveChunkAsync(buffer, ct);
}

private async Task SaveChunkAsync(List<Product> chunk, CancellationToken ct)
{
    db.Products.AddRange(chunk);
    await db.SaveChangesAsync(ct);
    db.ChangeTracker.Clear(); // forget these entities so memory doesn't grow
}

What each change does:

  • Chunking keeps each transaction small. A failure only loses the current chunk, and you can resume from there.
  • ChangeTracker.Clear() detaches everything after each save. The tracker never holds more than one chunk.
  • AutoDetectChangesEnabled = false stops EF from scanning tracked entities for changes, both when you call Add and when you call SaveChanges. New entities are still inserted, because Add marks them as Added straight away. It’s safe here because we only add new entities and never modify tracked ones. If you do edit a tracked entity with this setting off, SaveChanges won’t see the edit unless you call ChangeTracker.DetectChanges() yourself.

You can also experiment with the batch size. Microsoft’s guidance is that batching benefits on SQL Server tend to flatten out beyond around 40 statements, which is why the default is 42, but your mileage may vary. Benchmark before changing it:

options.UseSqlServer(connectionString, sql => sql.MaxBatchSize(100));

Cheaper keys make inserts cheaper

With an IDENTITY key, the database generates each ID, so EF has to read each one back after inserting. Two alternatives reduce that work:

// Option A: client-generated, sortable GUIDs (.NET 9+)
public class Product
{
    public Guid Id { get; set; } = Guid.CreateVersion7();
    // ...
}

// Option B: HiLo, where EF reserves a block of IDs from a database sequence up front
modelBuilder.Entity<Product>().Property(p => p.Id).UseHiLo("product_hilo");

Version 7 GUIDs are time-ordered, so they don’t fragment the clustered index the way random Guid.NewGuid() values do. HiLo keeps integer keys but fetches IDs in blocks instead of one at a time. Both let EF know the key before inserting.

Level 1 is good for: imports up to tens of thousands of rows, inserts that need EF features (navigations, generated values, interceptors, audit logic), and code you want to keep simple.

Level 2: SqlBulkCopy (SQL Server, millions of rows)

For real bulk loads, stop sending INSERT statements and use the database’s bulk load protocol. On SQL Server that’s SqlBulkCopy. It streams rows to the server in a compact binary format and writes them to the table in bulk. It skips everything EF does per entity, and typically outperforms even a well-tuned SaveChanges loop by a wide margin. Measure on your own data to see by how much.

You don’t need a separate connection string. You can borrow EF’s connection, and even its transaction:

using System.Data;
using System.Runtime.CompilerServices;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;

public async Task BulkInsertAsync(
    IAsyncEnumerable<Product> products,
    CancellationToken ct,
    string destinationTable = "dbo.Products")
{
    await db.Database.OpenConnectionAsync(ct);
    try
    {
        var connection = (SqlConnection)db.Database.GetDbConnection();
        var transaction = (SqlTransaction?)db.Database.CurrentTransaction?.GetDbTransaction();

        using var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, transaction)
        {
            DestinationTableName = destinationTable,
            BatchSize = 10_000,
            BulkCopyTimeout = 0 // no timeout: large loads can take minutes
        };

        bulkCopy.ColumnMappings.Add(nameof(Product.Sku), "Sku");
        bulkCopy.ColumnMappings.Add(nameof(Product.Name), "Name");
        bulkCopy.ColumnMappings.Add(nameof(Product.Price), "Price");
        bulkCopy.ColumnMappings.Add(nameof(Product.Stock), "Stock");
        bulkCopy.ColumnMappings.Add(nameof(Product.ImportedAtUtc), "ImportedAtUtc");

        await foreach (var table in ToDataTablesAsync(products, chunkSize: 50_000, ct))
        {
            await bulkCopy.WriteToServerAsync(table, ct);
        }
    }
    finally
    {
        await db.Database.CloseConnectionAsync();
    }
}

private static async IAsyncEnumerable<DataTable> ToDataTablesAsync(
    IAsyncEnumerable<Product> products,
    int chunkSize,
    [EnumeratorCancellation] CancellationToken ct)
{
    var table = CreateTable();

    await foreach (var p in products.WithCancellation(ct))
    {
        table.Rows.Add(p.Sku, p.Name, p.Price, p.Stock, p.ImportedAtUtc);

        if (table.Rows.Count == chunkSize)
        {
            yield return table;
            table = CreateTable();
        }
    }

    if (table.Rows.Count > 0)
        yield return table;

    static DataTable CreateTable()
    {
        var t = new DataTable();
        t.Columns.Add(nameof(Product.Sku), typeof(string));
        t.Columns.Add(nameof(Product.Name), typeof(string));
        t.Columns.Add(nameof(Product.Price), typeof(decimal));
        t.Columns.Add(nameof(Product.Stock), typeof(int));
        t.Columns.Add(nameof(Product.ImportedAtUtc), typeof(DateTime));
        return t;
    }
}

The DataTable chunks keep memory bounded: only 50,000 rows are in memory at a time, no matter how big the file is. For the absolute lowest memory use, you can pass SqlBulkCopy an IDataReader that reads straight from your source. Libraries like FastMember’s ObjectReader turn an IEnumerable<T> into one. When you use a reader, also set EnableStreaming = true so large nvarchar(max) or varbinary(max) values are streamed instead of buffered. (EnableStreaming has no effect with a DataTable.)

Notice we don’t map Id: it’s an identity column, so SQL Server generates it. The destinationTable parameter is there for the staging table pattern below.

SqlBulkCopy options that matter

Option What it does Use when
TableLock Takes a bulk-update lock on the table instead of row locks. Much faster, and enables minimal logging in some recovery models. Loading into a table nobody else is writing to at the same time, such as a staging table or a nightly load.
CheckConstraints Checks CHECK and foreign key constraints during the load. Off by default. You need the database to enforce integrity during the load.
FireTriggers Runs insert triggers. Off by default. Your table relies on triggers (auditing, denormalization).
KeepIdentity Uses the ID values you supply instead of generating new ones. Migrating data where IDs must be preserved.
BatchSize Rows per batch sent to the server. 0 means everything in one batch. Always set it, so a failure doesn’t roll back everything and memory stays steady on the server.
BulkCopyTimeout Seconds before timing out. The default is 30. Set to 0 or something large for big loads.

The two defaults that surprise people: constraints aren’t checked and triggers don’t fire. That’s part of why it’s fast. If you rely on either, turn them on explicitly, and expect it to be slower.

What you give up

  • No generated IDs come back. Your Product objects won’t have their Id set after the load. If you need IDs, for example to insert child rows next, see the staging table pattern below.
  • No EF features. No interceptors, no SavingChanges events, no audit fields set by your DbContext, no value converters. If your DbContext normally sets CreatedAtUtc in an interceptor, you have to set it yourself before the bulk copy.
  • Column mapping is manual and has to match your actual table, not your EF model. If a migration renames a column, your bulk copy code has to change too.

Level 2 is good for: hundreds of thousands to millions of rows on SQL Server, imports, ETL jobs, seeding large tables.

The staging table pattern: upserts and child rows

SqlBulkCopy only inserts. Real imports usually need more: insert new products, update existing ones (matched by Sku), and maybe skip invalid rows. The standard approach is to bulk copy into a staging table, then let the database do the merge in one set-based statement, all inside one transaction:

sequenceDiagram
    participant App
    participant Staging as staging.ProductImport
    participant Products as dbo.Products
    Note over App: Begin transaction
    App->>Staging: SqlBulkCopy streams every row
    App->>Products: MERGE from staging on Sku
    Note over Products: Update matches, insert new
    App->>Staging: TRUNCATE
    Note over App,Products: Commit, or roll back everything

The app sends the data once. The database does the matching, so no product is loaded into memory to decide between insert and update.

public async Task UpsertAsync(IAsyncEnumerable<Product> products, CancellationToken ct)
{
    await using var tx = await db.Database.BeginTransactionAsync(ct);

    // 1. Bulk copy into a staging table (same columns, no constraints, no indexes)
    await BulkInsertAsync(products, ct, destinationTable: "staging.ProductImport");

    // 2. Merge from staging into the real table in one statement
    await db.Database.ExecuteSqlAsync($"""
        MERGE dbo.Products AS target
        USING staging.ProductImport AS source
            ON target.Sku = source.Sku
        WHEN MATCHED THEN
            UPDATE SET target.Name = source.Name,
                       target.Price = source.Price,
                       target.Stock = source.Stock,
                       target.ImportedAtUtc = source.ImportedAtUtc
        WHEN NOT MATCHED BY TARGET THEN
            INSERT (Sku, Name, Price, Stock, ImportedAtUtc)
            VALUES (source.Sku, source.Name, source.Price, source.Stock, source.ImportedAtUtc);

        TRUNCATE TABLE staging.ProductImport;
        """, ct);

    await tx.CommitAsync(ct);
}

BulkInsertAsync picks up EF’s current transaction, so the bulk copy and the merge commit or roll back together. A failed merge doesn’t leave half-imported data behind.

The staging table also solves the “I need the generated IDs” problem: after the merge, join the staging table back to dbo.Products on Sku to get the new IDs, and use them to insert child rows the same way.

Two things to watch. First, if the same Sku appears twice in one feed, MERGE fails because one target row would be updated twice, so remove duplicates in staging first. Second, MERGE has known edge cases in SQL Server under heavy concurrency. Many teams prefer a separate UPDATE ... FROM followed by INSERT ... WHERE NOT EXISTS. Either works well with the staging approach.

PostgreSQL: binary COPY

On PostgreSQL the equivalent of SqlBulkCopy is COPY, and Npgsql exposes its fastest form, binary import:

using Npgsql;
using NpgsqlTypes;

await db.Database.OpenConnectionAsync(ct);
var connection = (NpgsqlConnection)db.Database.GetDbConnection();

await using var writer = await connection.BeginBinaryImportAsync(
    "COPY products (sku, name, price, stock, imported_at_utc) FROM STDIN (FORMAT BINARY)", ct);

await foreach (var p in ReadProductsAsync(path, ct))
{
    await writer.StartRowAsync(ct);
    await writer.WriteAsync(p.Sku, NpgsqlDbType.Text, ct);
    await writer.WriteAsync(p.Name, NpgsqlDbType.Text, ct);
    await writer.WriteAsync(p.Price, NpgsqlDbType.Numeric, ct);
    await writer.WriteAsync(p.Stock, NpgsqlDbType.Integer, ct);
    await writer.WriteAsync(p.ImportedAtUtc, NpgsqlDbType.TimestampTz, ct);
}

await writer.CompleteAsync(ct); // without this, the whole import is rolled back

This streams rows straight from your source to the database with almost no memory overhead. Don’t forget CompleteAsync(): if the writer is disposed without it, Npgsql cancels the import. Also note that timestamptz expects UTC: a DateTime with Kind set to Local or Unspecified is rejected.

Level 3: let a library do it

Writing SqlBulkCopy mappings by hand gets old, especially across many entity types. Several libraries read your EF Core model and do the mapping for you:

Library What it offers Licence
linq2db.EntityFrameworkCore BulkCopyAsync using your EF model’s mappings, across many databases. Also adds MERGE and other set-based operations. Open source (MIT)
EFCore.BulkExtensions BulkInsertAsync, BulkUpdateAsync, BulkInsertOrUpdateAsync, BulkDeleteAsync. Can return generated IDs to your objects (SetOutputIdentity). Dual licence. Not free for all commercial use, so check the current terms.
Entity Framework Extensions (ZZZ Projects) Very complete bulk insert, update, merge, and synchronize, with graph support. Commercial

With EFCore.BulkExtensions, for example, the whole import becomes this (products here is a List<Product>):

await db.BulkInsertAsync(products, new BulkConfig
{
    BatchSize = 10_000,
    SetOutputIdentity = true // fill in generated Ids on the objects (slower, uses a staging table internally)
}, cancellationToken: ct);

And with linq2db:

using LinqToDB.Data;
using LinqToDB.EntityFrameworkCore;

await db.BulkCopyAsync(new BulkCopyOptions { MaxBatchSize = 10_000 }, products, ct);

Check the licence before you add one of these to a commercial product. Several popular .NET libraries have moved to commercial or dual licences in recent years.

Level 3 is good for: teams doing bulk operations across many entity types, needing upserts or bulk updates, or wanting generated IDs back without writing the staging logic themselves.

Don’t forget bulk updates and deletes

Large imports often come with large updates (“mark everything not in today’s feed as discontinued”) or deletes (“remove last month’s staging data”). Don’t load entities just to change them. Since EF Core 7, ExecuteUpdateAsync and ExecuteDeleteAsync run as a single SQL statement:

// One UPDATE statement, no entities loaded or tracked
await db.Products
    .Where(p => p.ImportedAtUtc < importStartedAtUtc)
    .ExecuteUpdateAsync(s => s.SetProperty(p => p.Stock, 0), ct);

// One DELETE statement
await db.Products
    .Where(p => p.Stock == 0 && p.ImportedAtUtc < DateTime.UtcNow.AddYears(-1))
    .ExecuteDeleteAsync(ct);

EF Core 10 made ExecuteUpdateAsync easier to build dynamically, because it now accepts a regular lambda instead of an expression tree. So you can add setters conditionally:

await db.Products
    .Where(p => p.Sku == sku)
    .ExecuteUpdateAsync(s =>
    {
        s.SetProperty(p => p.ImportedAtUtc, DateTime.UtcNow);
        if (newPrice is not null)
            s.SetProperty(p => p.Price, newPrice.Value);
    }, ct);

Like SqlBulkCopy, these bypass the change tracker and SaveChanges interceptors, so any audit logic in an interceptor won’t run.

Things that slow down any bulk insert

These matter regardless of which approach you pick:

  1. Indexes. Every non-clustered index has to be updated for every inserted row. For a very large one-off load into an existing table, it can be faster to disable or drop non-clustered indexes, load, then rebuild them. Measure first, because rebuilding isn’t free either.
  2. Triggers and foreign keys. Both add work per row. That’s why SqlBulkCopy skips them by default.
  3. The transaction log. Huge single transactions make the log grow. Committing in batches (BatchSize, chunked saves) keeps it manageable. With TableLock and the right recovery model, SQL Server can minimally log bulk loads.
  4. Network distance. Run large imports close to the database, in the same region or ideally the same network, not from a laptop over VPN.
  5. Clustered key order. Inserting in clustered key order (sequential IDs, version 7 GUIDs) is faster than random order, because the database appends to the end of the index instead of splitting pages.

Measure, don’t guess

Performance varies a lot with row width, indexes, network latency, and hardware, so benchmark your own scenario rather than trusting anyone’s numbers, including mine. A simple Stopwatch around each approach with a realistic data set (100k rows is usually enough to see the difference) will tell you more than any blog post. For something more rigorous, use BenchmarkDotNet.

Also measure memory, not just time. The naive AddRange everything approach often fails on memory long before speed becomes a concern.

Choosing the right approach

%%{init: {"flowchart": {"wrappingWidth": 280}}}%%
flowchart TD
    A["How many rows?"]
    A --> B["Thousands<br/>AddRange + SaveChanges"]
    A --> C["Tens of thousands<br/>Level 1: chunked saves"]
    A --> D["Millions<br/>Which database?"]
    D --> E["SQL Server<br/>SqlBulkCopy"]
    D --> F["PostgreSQL<br/>binary COPY"]
    E --> G["Need upserts or Ids?"]
    F --> G
    G --> H["Yes<br/>Staging table + MERGE"]
    G --> I["No<br/>Bulk copy directly"]

Start at the top and stop at the first answer that fits. The table gives the same advice in more detail.

Situation Recommendation
A few hundred to a few thousand rows Plain AddRange + SaveChangesAsync. Don’t over-engineer it.
Up to tens of thousands of rows, or EF features needed Level 1: chunked SaveChanges + ChangeTracker.Clear() + AutoDetectChangesEnabled = false.
Hundreds of thousands to millions of rows, SQL Server Level 2: SqlBulkCopy with BatchSize, TableLock, and chunked or streamed input.
Same, PostgreSQL Npgsql binary COPY.
Insert-or-update (upsert) Bulk copy into a staging table, then MERGE or UPDATE + INSERT.
Need generated IDs for child rows Staging table and join back, or a library with output identity support.
Bulk operations across many entity types Level 3: linq2db (MIT) or EFCore.BulkExtensions (check the licence).
Large updates or deletes ExecuteUpdateAsync / ExecuteDeleteAsync, not load-modify-save.

Conclusion

EF Core’s SaveChanges is built for the typical unit of work: a handful of entities, change tracking, generated keys, and interceptors. Those same features become the bottleneck at scale: a million tracked entities, a million individual INSERTs, and a million IDs read back.

For moderate volumes, keep EF and tune it: save in chunks, clear the change tracker, turn off automatic change detection, and consider keys that don’t need a database round trip. For real bulk loads, step outside the change tracker and use what the database is built for: SqlBulkCopy on SQL Server, binary COPY on PostgreSQL, a staging table when you need upserts or generated IDs, or a library that wraps all of it. And for bulk changes to existing rows, use ExecuteUpdateAsync and ExecuteDeleteAsync instead of loading anything at all.

Pick the simplest approach that handles your volume, and measure with your own data before and after.

The complete project, with all 11 tests, is on GitHub.

Found this useful? Share it

XLinkedIn

Discussion