Repository navigation
Description
Databases usually provide various mechanisms for efficient bulk import of data from the client (e.g. .NET application) into the database. We already have issues tracking improving INSERT performance (#15059, #9118, #10443), but bulk import is a specialized scenario where the native database mechanisms work more efficiently (and often considerably so) than multiple INSERTs. Note also that this is different from bulk copy of data across tables within the database (INSERT ... SELECT, tracked by #27320).
Bulk import only allows targeting a table, so a simple method on DbSet should suffice (LINQ operators don't make sense here):
ctx.Blogs.ImportFrom(blogs);ImportFrom should accept an IEnumerable parameter; ImportFromAsync should have overloads accepting both IEnumerable and IAsyncEnumerable parameters. The method would pull entity instances and import them into the database table via the provider-specific mechanism.
Additional notes
- EF Core can provide a default implementation which just uses regular INSERTs (without tracking (#9118) and possibly with other optimizations). This would make the API always work, regardless whether a provider has provided a special implementation for it.
- This method would not be tracking. This typically isn't what's needed when bulk-importing, and the optimized import mechanisms don't typically allow reading back generated values (i.e. the IDs).
- Most databases also provide bulk import mechanisms which take CSV or other textual data. While this may be used under the hood (implementation detail), we wouldn't expose a user-facing API that deals with textual data; the focus is on an API where the user provides entity instances. An EF Core API accepting textual data would have no added value beyond just using the API directly.
- Similarly, some implementations allow importing data from a file on the database server - we again wouldn't expose an API for this as EF Core has no added value here.
- We may want to provide some sort of hook for allowing users to pass provider-specific parameterization of the import process (e.g. SqlBulkCopy allows controlling the batch size, the timeout...). For example, the SQL Server provider could expose an additional overload accepting a custom SqlServerBulkCopyOptions, and there would be a way for that overload to pipe the user-provided options down to the provider's implementation.
- Naming-wise, the word "import" is used because "copy" seems more ambiguous with copying across tables in the database (#27320).
Database support
- SQL Server - takes DataTable or IDataReader as input.
- PostgreSQL (Npgsql) - specialized API for binary import.
- MySql
- MySqlConnector - similar to SQL Server's SqlBulkCopy (but seems to support only DataTable/IEnumerable, no IDataReader).
- Official driver (seems to be CSV/tab-delimited only).
- SQLite: no special bulk import API apparently, but this dude wrote some tips on making inserts faster. It may make sense to wrap that in a bulk import implementation.
- Cosmos. This is a good reason to have this abstraction in core rather than relational.
Activity
AndriySvyryd commentedon Feb 2, 2022
We might need an overload with anonymous types for shadow properties.
Note that this would also allow inserts for keyless entity types. So we might need a non-collection overload too.
roji commentedon Feb 2, 2022
Yep..
Can you elaborate?
AndriySvyryd commentedon Feb 2, 2022
Just some sugar:
roji commentedon Feb 2, 2022
Ah I see - you're saying this would be the only way to insert keyless entity types (because we don't support them in Add/SaveChanges), so it makes sense to allow "bulk import" of a single instance... Right.
roji commentedon Feb 20, 2022
Note: we have #9118 for optionally not tracking after SaveChanges, which would unlock using SqlBulkCopy for standard SaveChanges. At that point, the advantage of a dedicated bulk import API (this issue) becomes bypassing the change tracking machinery, which may or may not be worth it.
yzorg commentedon Jun 24, 2022
Vote for taking a very close look at EFCore.BulkExtensions. The most underrated .net OSS libraries I use.
It already respects EFCore table name mappings and column/property mappings. It supports all the "batch" scenarios: "upsert", insert only (only new), and "delete if missing" (MERGE with DELETE clause). I've needed all those scenarios. All way faster than current EFCore for 10k+ rows (aka importing a full dataset daily/monthly/x). It supports pulling back new identity values into entities, but off by default, which I think is sensible for bulk scenarios. But if you can reuse roji's RETURNING work here might speed it up.
roji commentedon Jun 26, 2022
@yzorg thanks, yeah - we're aware of EFCore.BulkExtensions.
The plan specifically in this issue is only to wrap the database's native bulk import mechanism - SqlBulkCopy for SQL Server, binary COPY for PostgreSQL, etc. These lower-level API generally allow simply copying in large quantities of data into a table in the most efficient manner possible.
Various "merge" functionality such as upserting, deleting if missing, etc. are higher-level functionality which generally isn't covered by a database's bulk import mechanism, and are implemented by using additional database functionality. For example, it's typical to first use bulk import to efficiently copy data into a temporary table (e.g. via SqlBulkCopy), and then use MERGE to perform upsert/delete-if-missing/whatever between the temp table and the target table.
Such "compound" operations would be out of scope for this specific issue, but it would provide the first building block (bulk import). You could then use raw SQL to express whatever MERGE operation you want (we could possibly even provide an EF API for that, though I'm not sure it would be very valuable).
khteh commentedon Feb 17, 2023
https://www.npgsql.org/doc/copy.html#binary-copy is rather crude. I need to ingest tens of thousands of record from Excel sheet into the DB without any duplicate.
2 remaining items
AndriySvyryd commentedon Dec 4, 2024
PhenX commentedon Aug 18, 2025
I'd like to add a library I recently released, under MIT : https://phenx.github.io/PhenX.EntityFrameworkCore.BulkInsert/
It out-performs the other implementations in terms of speed and memory usage (see benchmarks, I unpublished Oracle and SQL Server results because of license issues)
ErikEJ commentedon Aug 18, 2025
@PhenX You should add it to the list of tools in the EF Docs
SkyDevLab commentedon Oct 16, 2026
I'd like to contribute to this proposal by implementing a focused prototype and adding performance benchmarks.
Would starting with the SQL Server provider using "SqlBulkCopy", behind a provider-neutral "DbSet.ImportFromAsync" API, be a useful direction?
I'd benchmark it against "AddRange"/"SaveChanges" across different batch sizes and test transaction behavior, value conversions, async streaming, and failure handling.
I'd appreciate maintainer feedback on the proposed direction before starting implementation.
AndriySvyryd commentedon Oct 21, 2026
@SkyDevLab Sounds good
SkyDevLab commentedon Oct 24, 2026
@AndriySvyryd I've completed an initial end-to-end prototype and benchmarked it against SQL Server LocalDB.
Prototype Architecture
ImportFromandImportFromAsyncoverloads toDbSet<TEntity>supporting bothIEnumerable<TEntity>andIAsyncEnumerable<TEntity>.IBulkImporterresolved via DI fromInternalDbSet.EntityDataReader<TEntity>): A customDbDataReaderwrapping the entity enumerators. It uses compiled property getters (IClrPropertyGetter) and evaluates value converters (property.FindTypeMapping()?.Converter) without generating change tracking entries. Store-generated identity properties are omitted by default (allowing SQL Server to generate keys), but can be preserved viaBulkImportOptions.KeepIdentity.SqlServerBulkImporter): UsesSqlBulkCopyand enlists in active EF Core transactions (RelationalConnection.CurrentTransaction?.GetDbTransaction()), respecting connection lifecycle management.Benchmark Results (SQL Server LocalDB)
Tested against standard
AddRangeAsync+SaveChangesAsyncwith an entity model containing numeric, string, and enum-converted properties:AddRange+SaveChangesImportFromAsync(SqlBulkCopy)Functional Validation
Verified with unit tests for
EntityDataReaderand live functional tests against LocalDB for:IDbContextTransactionrollback atomicityKeepIdentity = true)IAsyncEnumerable<TEntity>)The prototype branch is available here:
https://github.com/SkyDevLab/efcore/tree/feature/27333-bulk-import
Would you like me to open a draft PR against
dotnet/efcorefor review and further design discussion?AndriySvyryd commentedon Oct 26, 2026
@SkyDevLab The next step would be to measure the overhead of the new API vs calling the underlying API directly for each database, not just SQL Server (it doesn't need to be against a full implementation, just a PoC of what it would look like). We need to validate that the proposed API doesn't add too much overhead before we can decide whether it would be added in Core or should it be provider-specific.
SkyDevLab commentedon Oct 27, 2026
@AndriySvyryd I measured the overhead of the EF Core abstraction vs. calling the underlying driver API directly.
1. SQL Server:
DbSet.ImportFromAsyncvs. Direct RawSqlBulkCopyWe compared
DbSet.ImportFromAsyncagainst a direct ADO.NETSqlBulkCopycall using a hand-coded, zero-overheadDbDataReader(no reflection, no EF Core metadata, hardcoded ordinals) on SQL Server LocalDB:SqlBulkCopyImportFromAsyncIClrPropertyGetter) and value converters, keeping overhead around ~3.8% at 10,000 rows.2. PostgreSQL (
Npgsql) PoC & Overhead AnalysisFor PostgreSQL, the native mechanism is binary
COPYviaNpgsqlBinaryImporter:writer.StartRowAsync()andwriter.WriteAsync(p.Property)in a loop.IBulkImporterPoC: ResolvesIEntityTypemetadata to constructCOPY "table" ("col1", "col2") FROM STDIN (FORMAT BINARY)once at start, then iterates properties calling compiledIClrPropertyGetter.GetClrValue(entity)before passing towriter.WriteAsync(...).3. Fallback for Providers Without Native Bulk Protocols
We also added a default relational fallback (
RelationalBulkImporterinEFCore.Relational) that uses batched un-trackedINSERT INTO ... VALUES (...)parameterized statements. We validated this with functional tests on SQLite (250 rows imported in 31 ms), ensuring that non-SQL Server/PostgreSQL providers won't throwNotSupportedException.Given that the abstraction overhead is only ~3-4% and the design naturally accommodates both
DbDataReader-based bulk copiers (SQL Server, MySQL) and streaming binary writers (Npgsql), having the unified API in Core (DbSet.ImportFromAsync) appears well justified.Branch with the overhead benchmark and relational fallback:
https://github.com/SkyDevLab/efcore/tree/feature/27333-bulk-import
AndriySvyryd commentedon Oct 27, 2026
@SkyDevLab That sounds reasonable, go ahead and create the PR. Also, please share the code for the PostgreSQL PoC & benchmark.
khteh commentedon Oct 28, 2026
Why doesn't the overhead increase linearly? Does
DbSet.ImportFromAsynchandle relations, i.e., does it import into multiple tables? Does it make sense to have measurements for this?SkyDevLab commentedon Oct 28, 2026
@AndriySvyryd I've opened draft PR #39437 for the bulk import implementation and benchmarks:
#39437
PostgreSQL (
Npgsql) PoC & Benchmark CodeAs requested, here is the standalone PoC and benchmark script comparing direct
NpgsqlBinaryImporter(COPY ... FROM STDIN (FORMAT BINARY)) with an EF CoreIBulkImporteradapter:https://gist.github.com/SkyDevLab/30d4e99393ae8ba87f3fc671b4536aff
@khteh
SqlBulkCopy, binaryCOPY, etc.) are designed by the database engines to stream raw tabular data into a single destination table. They generally bypass change tracking and don't automatically round-trip database-generated foreign keys across child tables. Inserting full relational graphs is what standardSaveChanges()is designed for.