Skip to content

Prototype bulk import API (DbSet.ImportFromAsync) (#27333) - #39437

Draft
SkyDevLab wants to merge 8 commits into
dotnet:mainfrom
SkyDevLab:feature/27333-bulk-import
Draft

SkyDevLab wants to merge 8 commits into
dotnet:mainfrom
SkyDevLab:feature/27333-bulk-import

Conversation

@SkyDevLab

Copy link
Copy Markdown
Contributor

Addresses #27333.

Summary

This PR provides a prototype implementation of the bulk import feature tracked in #27333 for efficiently importing large quantities of client-side entity data directly into the database.

Proposed Architecture

  1. Public API Surface (Microsoft.EntityFrameworkCore):

    • Added non-tracking DbSet<TEntity>.ImportFrom and DbSet<TEntity>.ImportFromAsync overloads accepting IEnumerable<TEntity> and IAsyncEnumerable<TEntity>.
    • Configurable via BulkImportOptions (batch size, timeout, KeepIdentity).
  2. Provider SPI (Microsoft.EntityFrameworkCore.Update):

    • IBulkImporter: Scoped service resolved through InternalDbSet.
    • Default relational fallback: RelationalBulkImporter in EFCore.Relational executing batched un-tracked multi-row INSERT INTO ... VALUES (...) statements.
    • Tested on SQLite (SqliteBulkImportTest), ensuring providers without specialized bulk protocols do not fail with NotSupportedException.
  3. SQL Server Implementation (Microsoft.EntityFrameworkCore.SqlServer):

    • SqlServerBulkImporter: Integrates with Microsoft.Data.SqlClient.SqlBulkCopy.
    • EntityDataReader<TEntity>: A streaming DbDataReader adapter over entity enumerators evaluating compiled property getters (IClrPropertyGetter) and value converters (property.FindTypeMapping()?.Converter).
    • Transactional integration: Enlists in active EF Core IDbContextTransaction / SqlTransaction and participates in connection lifecycle management.
    • Tested on SQL Server LocalDB (SqlServerBulkImportTest).

Benchmarks & Overhead Analysis

1. SQL Server: ImportFromAsync vs SaveChanges (LocalDB)

Row Count AddRange + SaveChanges ImportFromAsync (SqlBulkCopy) Throughput Speedup Allocations
1,000 1,436 ms 49 ms ~29.1x faster Negligible
10,000 5,130 ms 565 ms ~9.1x faster 2 MB vs 47 MB (~23x reduction)

2. SQL Server: ImportFromAsync vs Direct Raw SqlBulkCopy (LocalDB)

Tested against raw ADO.NET SqlBulkCopy using a hand-coded, zero-reflection DbDataReader:

Row Count Direct Raw SqlBulkCopy EF Core ImportFromAsync Abstraction Overhead
10,000 236 ms 245 ms +9 ms (+3.8%)
50,000 787 ms 957 ms +170 ms

3. PostgreSQL (Npgsql) PoC

A standalone PoC and overhead benchmark comparing direct raw NpgsqlBinaryImporter (COPY ... FROM STDIN (FORMAT BINARY)) vs an EF Core IBulkImporter adapter has been published here:
https://gist.github.com/SkyDevLab/30d4e99393ae8ba87f3fc671b4536aff

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved bulk-import defects can discard client-generated keys, skip rows, omit mapped values, and bypass database constraints, causing import failures or silent data loss.

12 open issues
What changed in this PR

Prototypes non-tracking bulk import for #27333, adding a core provider contract, a relational INSERT fallback, and a SQL Server implementation using SqlBulkCopy.

Changes:

  • Adds synchronous and asynchronous DbSet import APIs with batch size, timeout, and identity-preservation options.
  • Implements relational batching and SQL Server entity streaming with transaction integration.
  • Adds reader tests, provider functional tests, and performance comparisons.
File Description
test/​EFCore.SqlServer.Tests/​Update/​EntityDataReaderTest.cs Tests identity selection, conversions, nulls, and async reading.
test/​EFCore.SqlServer.FunctionalTests/​Update/​SqlServerBulkImportTest.cs Adds import scenarios and performance comparisons.
test/​EFCore.Sqlite.FunctionalTests/​Update/​SqliteBulkImportTest.cs Exercises the relational fallback on SQLite.
src/​EFCore/​Update/​IBulkImporter.cs Defines the provider bulk-import contract.
src/​EFCore/​Update/​BulkImportOptions.cs Defines import configuration options.
src/​EFCore/​Internal/​InternalDbSet.cs Delegates import calls to the provider service.
src/​EFCore/​Infrastructure/​EntityFrameworkServicesBuilder.cs Declares the importer’s scoped lifetime.
src/​EFCore/​DbSet.cs Exposes synchronous and asynchronous import overloads.
src/​EFCore.SqlServer/​Update/​Internal/​SqlServerBulkImporter.cs Implements imports using SqlBulkCopy.
src/​EFCore.SqlServer/​Update/​Internal/​EntityDataReader.cs Adapts entity sequences into database-reader rows.
src/​EFCore.SqlServer/​Extensions/​SqlServerServiceCollectionExtensions.cs Registers the SQL Server importer.
src/​EFCore.Relational/​Update/​Internal/​RelationalBulkImporter.cs Implements batched INSERT fallback imports.
src/​EFCore.Relational/​Infrastructure/​EntityFrameworkRelationalServicesBuilder.cs Registers the relational fallback.
benchmark/​EFCore.SqlServer.Benchmarks/​UpdatePipeline/​BulkImportSqlServerTests.cs Compares bulk import with tracked SaveChanges.

Review effort: Balanced

continue;
}

var getter = property.GetGetter();
Comment on lines +139 to +142
if (columns.Count == 0)
{
return;
}
bool keepIdentity)
{
var list = new List<PropertyColumnMapping>();
foreach (var property in entityType.GetProperties())
Comment on lines +86 to +88
if (property.IsPrimaryKey()
&& property.ValueGenerated != ValueGenerated.Never
&& !keepIdentity)
continue;
}

var getter = property.GetGetter();

var columnList = string.Join(", ", columns.Select(c => c.DelimitedColumnName));

var shouldManageTransaction = _connection.CurrentTransaction is null;

sqlBuilder.Append(';');

var rawSqlCommand = _rawSqlCommandBuilder.Build(sqlBuilder.ToString(), parameters);
Comment on lines +251 to +252
var rawSqlCommand = _rawSqlCommandBuilder.Build(sqlBuilder.ToString(), parameters);
await rawSqlCommand.RelationalCommand.ExecuteNonQueryAsync(
StoreObjectIdentifier storeObject,
bool keepIdentity)
{
_asyncEnumerator = source.GetAsyncEnumerator();

var schema = entityType.GetSchema();
var storeObject = StoreObjectIdentifier.Table(tableName, schema);
var destinationTable = schema is not null ? $"[{schema}].[{tableName}]" : $"[{tableName}]";
- Move IBulkImporter from CoreServices to RelationalServices
- Update EFCore.baseline.json via ApiBaselineTest
- Preserve client-generated keys and handle complex/shadow properties
- Delimit and escape SQL identifiers and brackets
- Respect ambient and enlisted transactions in RelationalBulkImporter
- Apply BulkImportOptions.Timeout and SqlBulkCopyOptions defaults
@vslee

vslee commented Nov 2, 2026

Copy link
Copy Markdown

Hi @MaceWindu @sdanyliv @jogibear9988 @borisdj @yangzhongke @SebastianStehle @PhenX @JonathanMagnan. As authors of community implementations, any comments on this PR?

@PhenX

PhenX commented Nov 2, 2026

Copy link
Copy Markdown

Thanks for the ping, and nice work getting this started. The API shape matches #27333 well, and IBulkImporter is a sensible extension point for providers, but there is still a lot of work to get to the EFCore standards in my opinion.

When I built PhenX.EntityFrameworkCore.BulkInsert, the copy itself was the easy part. Deciding which columns to write was hard. A few things I'd look at, after an investigation, with some Claude help:

  • Column selection vs SaveChanges:
    • HasDefaultValue/HasDefaultValueSql columns are always sent, so database defaults never apply.
    • Guid keys with NEWSEQUENTIALID() are inserted as Guid.Empty.
    • HiLo keys are left out, but the column has no database default to fill them.
    • Client-side value generators never run.
  • Fail loudly: owned types, JSON columns, entity splitting, TPT, shadow FKs and derived types inserted through a base DbSet are skipped or get the wrong discriminator without any error. I'd throw until they're supported.
  • Fallback parameters: parameter types come from the CLR value through IRawSqlCommandBuilder, so the property's store type is lost (e.g. jsonb). The hardcoded @p prefix won't work on Oracle.
  • Consistency:
    • The fallback runs in a transaction but the SqlBulkCopy path doesn't, so a failure with BatchSize set leaves partial commits.
    • BulkCopyTimeout stays at 30s instead of using EF's CommandTimeout.
    • The bulk copy path skips EF logging and interceptors.
  • Sync path: it blocks on the async code. A real sync path would match the rest of EF.
  • Options: FireTriggers, TableLock and provider-specific options, as the issue proposes.

On overhead, a BenchmarkDotNet comparison against raw SqlBulkCopy/COPY would be more convincing than Stopwatch tests, especially given the +22% at 50k rows.

I'm happy to share what we learned on edge cases (spatial types, type mapping for PostgreSQL binary COPY, returning generated IDs via temp tables) if that helps.

@JonathanMagnan

Copy link
Copy Markdown

I was about to comment, but after reading @PhenX's answer, I realized that pretty much all my concerns were already covered by him

He did a great job reviewing the code, highlighting all the major concerns that need to be addressed to meet EF Core standards

@yangzhongke

Copy link
Copy Markdown

What an awesome work!
I'm on holiday, so I'm not available to thoroughly review this PR until the end of November.

I just did a rough check of your PR and reviewed @PhenX great comments. That's all I can think of for now, and I hope this PR can be merged soon.

@MaceWindu

MaceWindu commented Nov 3, 2026 •

Copy link
Copy Markdown

Based on our expertise in this area for multiple databases/providers in LinqToDB, I've asked Claude to review this design (especially sync/async and providers support areas). Most of it sound reasonable, depending on how much flexibility EFCore team wants here.


Notes from the linq2db side (we maintain BulkCopy across ~20 providers). Column selection and model coverage are already in PhenX's review; this covers the SPI shape, async, and provider support.

SPI shape

IBulkImporter is one monolithic method per provider, replaced wholesale via TryAdd. Every provider has to re-implement column planning, transaction handling, fallback and logging. The PR already has two diverging copies of column selection: RelationalBulkImporter and EntityDataReader.CreateMappings; only the latter checks SqlServerValueGenerationStrategy.IdentityColumn (L100-L105).

What worked for us: a shared base (BasicBulkCopy) with three overridable strategies chained as defaults — provider-specific → multi-row INSERT → row-by-row (L80-L120) — plus one shared column list and one shared reader. A provider overrides only the native path and inherits everything else, including the fallback.

Async

  1. Sync API is sync-over-async. Import is ImportAsync(...).GetAwaiter().GetResult() in both RelationalBulkImporter and SqlServerBulkImporter, and the fallback additionally lifts IEnumerable into a synthetic IAsyncEnumerable. The sync call does real async I/O and blocks a pool thread on it. We keep separate sync and async paths per strategy; the only sync-over-async left is the unavoidable direction — a sync-only native API fed an async source (BulkCopyReader.MoveNext, e.g. the DuckDB appender, DuckDBBulkCopy).
  2. Rollback on cancellation is skipped. The catch calls RollbackAsync(cancellationToken); when the failure is the cancellation, that throws immediately and only the implicit rollback on dispose remains. Use CancellationToken.None there.
  3. Cancellation of sync sources is a no-op. AsAsyncEnumerable has no [EnumeratorCancellation], so .WithCancellation(cancellationToken) does nothing for them; the token is only observed per batch.
  4. The reader's sync Read() blocks over an async source (EntityDataReader). SqlBulkCopy.WriteToServerAsync happens to call ReadAsync, but Oracle / DB2 / HANA / Informix bulk-copy APIs are sync and will call Read() per row. The importer needs to know which mode the native API runs in, and the SPI gives it no way to express that.
  5. Streaming source vs. retrying execution strategy. An IAsyncEnumerable cannot be replayed, so a retrying IExecutionStrategy cannot wrap the import. The PR does not go through IExecutionStrategy at all; this should be an explicit decision (throw, or document as non-retriable), not an accident.

Provider support

  1. The relational fallback is SQL Server–shaped and not portable. Its limits — ≤1000 rows, 1000 / columns parameters (L172-L173) — are SQL Server's, yet SQL Server never takes this path. Multi-row VALUES does not exist on Oracle (before 23ai), Firebird, Informix, SAP HANA or Access. We need three row-constructor dialects — VALUES list (MultipleRowsCopy1), UNION ALL SELECT … FROM <dummy> (MultipleRowsCopy2, MultipleRowsCopy3), Oracle INSERT ALL — plus per-provider MaxParameters / MaxSqlLength (e.g. Access) enforced while the batch is built (MultipleRowsCopyHelper), and a literals-vs-parameters switch. In EF terms: limits, row-constructor dialect and parameter naming (the hardcoded @p) as virtual members on a relational base class.
  2. No fallback from the native path. (SqlConnection)_connection.DbConnection / (SqlTransaction?)…GetDbTransaction() are hard casts; a connection wrapped by an interceptor or a profiler throws InvalidCastException. We unwrap via TryGetProviderConnection and fall back to multi-row when it fails (SqlServerBulkCopy, L100-L105). With wholesale service replacement, an EF provider cannot even delegate to the relational fallback.
  3. EntityDataReader is in the wrong assembly and carries too little type information. It lives in EFCore.SqlServer but is provider-neutral: our single BulkCopyReader feeds SQL Server, MySQL, Oracle, DB2, Informix, SAP HANA, Sybase, ClickHouse and YDB. It also exposes CLR types only — GetDataTypeName returns the CLR type name. Npgsql binary COPY takes no reader at all and needs an NpgsqlDbType or store type name per column (PostgreSQLBulkCopy.BuildTypes). The per-column plan handed to providers must carry the RelationalTypeMapping / store type, not just a getter and a converter.
  4. Build the column plan from the relational model. Walking GetFlattenedProperties() + GetColumnName(storeObject) misses table splitting, TPT (several tables per row) and owned types. Planning from GetTableMappings() / IColumnMapping either handles them or at least makes "unsupported" detectable, so it can throw.
  5. Options are too thin for a provider-neutral contract. Compared with BulkCopyOptions: no TableLock, FireTriggers, UseInternalTransaction, CheckConstraints (hardcoded on, L109; ours map at L168-L173); no progress callback with abort; no destination table override (the import-to-staging-table-then-MERGE workflow is the main bulk use case); no strategy selector (BulkCopyType); and nothing is returned (BulkCopyRowsCopied). The timeout default should follow the connection's CommandTimeout (ours).
  6. No capability negotiation. Unsupported combinations are silently ignored — KeepIdentity on the fallback, PostgreSQL GENERATED ALWAYS identity needing OVERRIDING SYSTEM VALUE. We throw for an unsupported strategy/option combination (KeepIdentity in row-by-row).
  7. Minor:

Suggested shape

  • RelationalBulkImporter as a base class with virtual strategy hooks: native → multi-row → row-by-row.
  • A shared column plan built from table mappings, carrying store types, in EFCore.Relational.
  • A shared async-aware entity reader in EFCore.Relational.
  • Native path tried first, falling back automatically when the connection is not the native type or an option combination is unsupported.
  • Separate sync and async paths.
  • Explicit throw-on-unsupported rules per model feature and per option.

@SkyDevLab

Copy link
Copy Markdown
Contributor Author

Thank you @vslee for looping in the community authors, and a huge thank you to @PhenX, @MaceWindu, @JonathanMagnan, and @yangzhongke for taking the time to share your real-world insights and architectural experience!

The feedback is spot-on and directly aligns with making this feature production-ready and idiomatic to EF Core. Here is the roadmap of improvements being implemented based on your suggestions:

  1. Shared RelationalBulkImporter Base Architecture:
    • Refactoring RelationalBulkImporter in EFCore.Relational into an extensible base class with virtual strategy hooks (CanExecuteNativeImport, ExecuteNativeImportAsync, ExecuteBatchInsertAsync). Providers like SQL Server can override the native hook while seamlessly delegating or falling back to the multi-row insert batch pipeline.
  2. Promoting EntityDataReader to EFCore.Relational:
    • Moving the reader to EFCore.Relational so all ADO.NET providers can share a single, zero-allocation streaming reader.
    • Retaining full RelationalTypeMapping and database store type information on mapped columns (essential for PostgreSQL binary COPY, Oracle, and spatial types).
  3. Fail Loudly on Unsupported Mappings:
    • Adding explicit model validation upfront: throwing descriptive NotSupportedException for entity splitting, TPT (Table-Per-Type across multiple tables), and owned navigation hierarchies until full multi-table planning is supported.
  4. True Sync Pipeline:
    • Implementing a dedicated synchronous enumeration and execution loop rather than sync-over-async blocking.
  5. Consistency & Options:
    • Inheriting default timeouts from DbContext.Database.GetCommandTimeout().
    • Wrapping multi-batch imports in consistent transaction boundaries by default.

Working on pushing these refinements to the branch. Thank you all again for the valuable guidance!

- Promote EntityDataReader to EFCore.Relational with type mapping retention and value caching
- Refactor RelationalBulkImporter base class with native execution and batch insert hooks
- Add fail-loudly validation for TPT, entity splitting, and JSON entities
- Add DEFAULT VALUES fallback when no writable columns exist
- Add BulkImportOptions: TableLock, FireTriggers, and DestinationTableName
- Update EFCore public API baseline
- Add relational and SQLite functional test suites for computed columns, client-generated GUIDs, and identity options
@yangzhongke

Copy link
Copy Markdown

Sorry for the late reply.

Have we settled on the naming yet? I'm not sure that ImportFrom conveys the performance benefits of bulk copying. Could we consider BulkCopyFrom or something similar instead?

Comment thread src/EFCore/DbSet.cs
=> false;

/// <summary>
/// Imports the specified entities directly into the database table without change tracking.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A minor English grammar issue, add "using" after "without":
Imports the specified entities directly into the database table without using change tracking.

Comment thread src/EFCore/DbSet.cs
=> throw new NotSupportedException();

/// <summary>
/// Asynchronously imports the specified entities directly into the database table without change tracking.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A minor English grammar issue, add "using" after "without":
Imports the specified entities directly into the database table without using change tracking.

Comment thread src/EFCore/DbSet.cs
=> ImportFromAsync(entities, options: null, cancellationToken);

/// <summary>
/// Asynchronously imports the specified entities directly into the database table without change tracking.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as above

Comment thread src/EFCore/DbSet.cs
=> throw new NotSupportedException();

/// <summary>
/// Asynchronously imports the specified entities stream directly into the database table without change tracking.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as above

Comment thread src/EFCore/DbSet.cs
=> ImportFromAsync(entities, options: null, cancellationToken);

/// <summary>
/// Asynchronously imports the specified entities stream directly into the database table without change tracking.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as above

Comment thread src/EFCore/DbSet.cs
/// </summary>
/// <param name="entities">The entities to import.</param>
/// <param name="options">Options to configure the bulk import operation.</param>
public virtual void ImportFrom(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As I said just now, will "BulkCopyFrom" be better?

/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public sealed class EntityDataReader<TEntity> : DbDataReader

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you considered some DB provider not supporting DbReader as the parameter of Write, for example, in Npgsql, it only supports NpgsqlBinaryImporter like:

// 1. Start the binary import stream
await using var writer = await conn.BeginBinaryImportAsync(
    "COPY my_table (id, name, created_at) FROM STDIN (FORMAT BINARY)");

// 2. Write rows one by one
await writer.StartRowAsync();
await writer.WriteAsync(1, NpgsqlDbType.Integer);
await writer.WriteAsync("Alice", NpgsqlDbType.Text);
await writer.WriteAsync(DateTime.UtcNow, NpgsqlDbType.TimestampTz);

await writer.StartRowAsync();
await writer.WriteAsync(2, NpgsqlDbType.Integer);
await writer.WriteNullAsync(); // Handle NULLs explicitly
await writer.WriteAsync(DateTime.UtcNow, NpgsqlDbType.TimestampTz);

// 3. Finalize and commit the import (if omitted, changes are rolled back on dispose)
await writer.CompleteAsync();

Using your proposed API, it would be hard to build the counterpart for Npgsql.

@yangzhongke yangzhongke Nov 25, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Never mind, I think Npgsql provider can create a customed NpgBulk copier around BeginBinaryImportAsync to support WriteToServer(dbreader)

Please ignore this comment

var (delimitedTableName, storeObject) = GetTableAndStoreObject(entityType, options);
var keepIdentity = options?.KeepIdentity ?? false;

var reader = new EntityDataReader<TEntity>(entityType, entities, storeObject, keepIdentity, cancellationToken: cancellationToken);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"using var reader"

return;
}

var maxBatchSize = options?.BatchSize ?? 1000;

@yangzhongke yangzhongke Nov 26, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

magic number.
could you define it as a const variable?


var batch = new List<TEntity>(maxRowsPerBatch);

await foreach (var entity in entities.WithCancellation(cancellationToken).ConfigureAwait(false))

@yangzhongke yangzhongke Nov 26, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

entities is an IEnumerable rather than IAsyncEnumerable, does WithCancellation() add any values here?

/// <summary>
/// Options for configuring bulk import operations.
/// </summary>
public record BulkImportOptions

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you change it into a virtual class, so that different provider can add more option items to it?

var first = await context.Products.OrderBy(p => p.Id).FirstAsync();
Assert.Equal("Product 1", first.Name);
Assert.Equal(1.5m, first.Price);
Assert.Equal(ProductCategory.Books, first.Category);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you have assertion to check if the items are inserted using BulkCopy rather than falling back to "insert into"?

@SkyDevLab SkyDevLab Nov 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — we didn't have an assertion for that before. Added TestSqlLoggerFactory assertions in dc4165cd9e:

  1. Can_bulk_import_entities_basic now asserts that zero INSERT INTO SQL commands are executed during ImportFromAsync, proving native SqlBulkCopy over TDS is used.
  2. Added Can_fallback_to_batched_insert_when_native_import_disabled to verify that disabling the native path triggers the batched INSERT INTO fallback and logs the expected SQL commands.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants