Skip to content

Bulk import for efficient importing of data from the client into the database #27333

Description

@roji

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.

Community implementations

Activity

  1. AndriySvyryd commented on Feb 2, 2022

    @AndriySvyryd
    Member

    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.

  2. roji commented on Feb 2, 2022

    @roji
    MemberAuthor

    We might need an overload with anonymous types for shadow properties.

    Yep..

    Note that this would also allow inserts for keyless entity types. So we might need a non-collection overload too.

    Can you elaborate?

  3. AndriySvyryd commented on Feb 2, 2022

    @AndriySvyryd
    Member

    Can you elaborate?

    Just some sugar:

    ctx.KeylessBlogs.ImportFrom(new KeylessBlog());
  4. roji commented on Feb 2, 2022

    @roji
    MemberAuthor

    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.

  5. added this to the Backlog milestone on Feb 4, 2022
  6. roji commented on Feb 20, 2022

    @roji
    MemberAuthor

    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.

  7. yzorg commented on Jun 24, 2022

    @yzorg

    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.

  8. roji commented on Jun 26, 2022

    @roji
    MemberAuthor

    @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).

  9. khteh commented on Feb 17, 2023

    @khteh

    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.

  10. 2 remaining items

  11. AndriySvyryd commented on Dec 4, 2024

    @AndriySvyryd
  12. added theissue type on Jun 15, 2025
  13. marked Way Faster Inserts #31310 as a duplicate of this issue on Jun 16, 2025
  14. marked ExecuteInsert (bulk insert) #29994 as a duplicate of this issue on Jun 16, 2025
  15. PhenX commented on Aug 18, 2025

    @PhenX

    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)

  16. ErikEJ commented on Aug 18, 2025

    @ErikEJ
    Contributor

    @PhenX You should add it to the list of tools in the EF Docs

  17. SkyDevLab commented on Oct 16, 2026

    @SkyDevLab
    Contributor

    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.

  18. AndriySvyryd commented on Oct 21, 2026

    @AndriySvyryd
    Member

    @SkyDevLab Sounds good

  19. SkyDevLab commented on Oct 24, 2026

    @SkyDevLab
    Contributor

    @AndriySvyryd I've completed an initial end-to-end prototype and benchmarked it against SQL Server LocalDB.

    Prototype Architecture

    • API Surface: Added non-tracking ImportFrom and ImportFromAsync overloads to DbSet<TEntity> supporting both IEnumerable<TEntity> and IAsyncEnumerable<TEntity>.
    • Provider SPI: Introduced a scoped IBulkImporter resolved via DI from InternalDbSet.
    • Streaming Adapter (EntityDataReader<TEntity>): A custom DbDataReader wrapping 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 via BulkImportOptions.KeepIdentity.
    • SQL Server Implementation (SqlServerBulkImporter): Uses SqlBulkCopy and enlists in active EF Core transactions (RelationalConnection.CurrentTransaction?.GetDbTransaction()), respecting connection lifecycle management.

    Benchmark Results (SQL Server LocalDB)

    Tested against standard AddRangeAsync + SaveChangesAsync with an entity model containing numeric, string, and enum-converted properties:

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

    Functional Validation

    Verified with unit tests for EntityDataReader and live functional tests against LocalDB for:

    • Batching and custom value conversions
    • Explicit IDbContextTransaction rollback atomicity
    • Identity column preservation (KeepIdentity = true)
    • Async streaming consumption (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/efcore for review and further design discussion?

  20. AndriySvyryd commented on Oct 26, 2026

    @AndriySvyryd
    Member

    @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.

  21. SkyDevLab commented on Oct 27, 2026

    @SkyDevLab
    Contributor

    @AndriySvyryd I measured the overhead of the EF Core abstraction vs. calling the underlying driver API directly.

    1. SQL Server: DbSet.ImportFromAsync vs. Direct Raw SqlBulkCopy

    We compared DbSet.ImportFromAsync against a direct ADO.NET SqlBulkCopy call using a hand-coded, zero-overhead DbDataReader (no reflection, no EF Core metadata, hardcoded ordinals) on SQL Server LocalDB:

    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
    • The one-time metadata resolution and ordinal mapping cost is negligible.
    • The per-row cost is strictly the invocation of compiled property getters (IClrPropertyGetter) and value converters, keeping overhead around ~3.8% at 10,000 rows.

    2. PostgreSQL (Npgsql) PoC & Overhead Analysis

    For PostgreSQL, the native mechanism is binary COPY via NpgsqlBinaryImporter:

    • Direct Npgsql: Calling writer.StartRowAsync() and writer.WriteAsync(p.Property) in a loop.
    • EF Core IBulkImporter PoC: Resolves IEntityType metadata to construct COPY "table" ("col1", "col2") FROM STDIN (FORMAT BINARY) once at start, then iterates properties calling compiled IClrPropertyGetter.GetClrValue(entity) before passing to writer.WriteAsync(...).
    • Overhead: For 10,000 entities with 5 columns (50,000 delegate invocations), the compiled property getter CPU overhead is ~0.2–0.4 ms, which is dwarfed by network transfer and database write latency.

    3. Fallback for Providers Without Native Bulk Protocols

    We also added a default relational fallback (RelationalBulkImporter in EFCore.Relational) that uses batched un-tracked INSERT 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 throw NotSupportedException.

    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

  22. AndriySvyryd commented on Oct 27, 2026

    @AndriySvyryd
    Member

    @SkyDevLab That sounds reasonable, go ahead and create the PR. Also, please share the code for the PostgreSQL PoC & benchmark.

  23. khteh commented on Oct 28, 2026

    @khteh

    27. 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**
    

    Why doesn't the overhead increase linearly? Does DbSet.ImportFromAsync handle relations, i.e., does it import into multiple tables? Does it make sense to have measurements for this?

  24. SkyDevLab commented on Oct 28, 2026

    @SkyDevLab
    Contributor

    @AndriySvyryd I've opened draft PR #39437 for the bulk import implementation and benchmarks:
    #39437

    PostgreSQL (Npgsql) PoC & Benchmark Code

    As requested, here is the standalone PoC and benchmark script comparing direct NpgsqlBinaryImporter (COPY ... FROM STDIN (FORMAT BINARY)) with an EF Core IBulkImporter adapter:
    https://gist.github.com/SkyDevLab/30d4e99393ae8ba87f3fc671b4536aff


    @khteh

    Why doesn't the overhead increase linearly? Does DbSet.ImportFromAsync handle relations, i.e., does it import into multiple tables? Does it make sense to have measurements for this?

    1. Targeting Single Tables: As discussed earlier in this issue, native database bulk copy mechanisms (SqlBulkCopy, binary COPY, 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 standard SaveChanges() is designed for.
    2. Scaling: The difference between 10k and 50k rows reflects socket buffer streaming, network packet batching in the ADO.NET driver, and memory management during large allocations rather than per-row CPU scaling.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions