Repository navigation
Conversation
There was a problem hiding this comment.
🟡 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
Exclude computed columns from bulk INSERTs · New Insert rows when entities have no writable columns · New Include complex-property values in bulk imports · New Preserve client-generated keys during bulk import · New Handle shadow discriminators without CLR getters · New Use the complete resolved type converter · New Enable constraint checks and preserve nulls by default · New Participate in ambient and enlisted transactions · New Escape literal braces in SQL identifiers · New Apply import timeout to relational fallback commands · New Pass cancellation tokens to async source enumeration · New Escape closing brackets in SQL identifiers · New
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
DbSetimport 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(); |
| if (columns.Count == 0) | ||
| { | ||
| return; | ||
| } |
| bool keepIdentity) | ||
| { | ||
| var list = new List<PropertyColumnMapping>(); | ||
| foreach (var property in entityType.GetProperties()) |
| 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); |
| 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
|
Hi @MaceWindu @sdanyliv @jogibear9988 @borisdj @yangzhongke @SebastianStehle @PhenX @JonathanMagnan. As authors of community implementations, any comments on this PR? |
|
Thanks for the ping, and nice work getting this started. The API shape matches #27333 well, and 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:
On overhead, a BenchmarkDotNet comparison against raw 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. |
|
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 |
|
What an awesome work! 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. |
|
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 SPI shape
What worked for us: a shared base ( Async
Provider support
Suggested shape
|
|
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:
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
|
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? |
| => false; | ||
|
|
||
| /// <summary> | ||
| /// Imports the specified entities directly into the database table without change tracking. |
There was a problem hiding this comment.
A minor English grammar issue, add "using" after "without":
Imports the specified entities directly into the database table without using change tracking.
| => throw new NotSupportedException(); | ||
|
|
||
| /// <summary> | ||
| /// Asynchronously imports the specified entities directly into the database table without change tracking. |
There was a problem hiding this comment.
A minor English grammar issue, add "using" after "without":
Imports the specified entities directly into the database table without using change tracking.
| => ImportFromAsync(entities, options: null, cancellationToken); | ||
|
|
||
| /// <summary> | ||
| /// Asynchronously imports the specified entities directly into the database table without change tracking. |
| => throw new NotSupportedException(); | ||
|
|
||
| /// <summary> | ||
| /// Asynchronously imports the specified entities stream directly into the database table without change tracking. |
| => ImportFromAsync(entities, options: null, cancellationToken); | ||
|
|
||
| /// <summary> | ||
| /// Asynchronously imports the specified entities stream directly into the database table without change tracking. |
| /// </summary> | ||
| /// <param name="entities">The entities to import.</param> | ||
| /// <param name="options">Options to configure the bulk import operation.</param> | ||
| public virtual void ImportFrom( |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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); |
| return; | ||
| } | ||
|
|
||
| var maxBatchSize = options?.BatchSize ?? 1000; |
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
entities is an IEnumerable rather than IAsyncEnumerable, does WithCancellation() add any values here?
| /// <summary> | ||
| /// Options for configuring bulk import operations. | ||
| /// </summary> | ||
| public record BulkImportOptions |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
do you have assertion to check if the items are inserted using BulkCopy rather than falling back to "insert into"?
There was a problem hiding this comment.
Good catch — we didn't have an assertion for that before. Added TestSqlLoggerFactory assertions in dc4165cd9e:
Can_bulk_import_entities_basicnow asserts that zeroINSERT INTOSQL commands are executed duringImportFromAsync, proving nativeSqlBulkCopyover TDS is used.- Added
Can_fallback_to_batched_insert_when_native_import_disabledto verify that disabling the native path triggers the batchedINSERT INTOfallback and logs the expected SQL commands.


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
Public API Surface (
Microsoft.EntityFrameworkCore):DbSet<TEntity>.ImportFromandDbSet<TEntity>.ImportFromAsyncoverloads acceptingIEnumerable<TEntity>andIAsyncEnumerable<TEntity>.BulkImportOptions(batch size, timeout,KeepIdentity).Provider SPI (
Microsoft.EntityFrameworkCore.Update):IBulkImporter: Scoped service resolved throughInternalDbSet.RelationalBulkImporterinEFCore.Relationalexecuting batched un-tracked multi-rowINSERT INTO ... VALUES (...)statements.SqliteBulkImportTest), ensuring providers without specialized bulk protocols do not fail withNotSupportedException.SQL Server Implementation (
Microsoft.EntityFrameworkCore.SqlServer):SqlServerBulkImporter: Integrates withMicrosoft.Data.SqlClient.SqlBulkCopy.EntityDataReader<TEntity>: A streamingDbDataReaderadapter over entity enumerators evaluating compiled property getters (IClrPropertyGetter) and value converters (property.FindTypeMapping()?.Converter).IDbContextTransaction/SqlTransactionand participates in connection lifecycle management.SqlServerBulkImportTest).Benchmarks & Overhead Analysis
1. SQL Server:
ImportFromAsyncvsSaveChanges(LocalDB)AddRange+SaveChangesImportFromAsync(SqlBulkCopy)2. SQL Server:
ImportFromAsyncvs Direct RawSqlBulkCopy(LocalDB)Tested against raw ADO.NET
SqlBulkCopyusing a hand-coded, zero-reflectionDbDataReader:SqlBulkCopyImportFromAsync3. PostgreSQL (
Npgsql) PoCA standalone PoC and overhead benchmark comparing direct raw
NpgsqlBinaryImporter(COPY ... FROM STDIN (FORMAT BINARY)) vs an EF CoreIBulkImporteradapter has been published here:https://gist.github.com/SkyDevLab/30d4e99393ae8ba87f3fc671b4536aff