Skip to content

Non-tracking ExecuteInsert #29897

Open

Description

@roji

EF Core 7.0 introduced ExecuteUpdate and ExecuteDelete, which are ways of updating and deleting database rows without passing through change tracking. For inserts, it's still necessary to go through the change tracker (Add and then SaveChanges).

There are two main advantages to this:

  1. Ease-of-use. For the common task of adding a single entity, this would be a single line instead of two.
  2. Performance. Not passing through the change tracker would remove that overhead.

Notes:

  • We should probably allow a single call can insert multiple rows, since SQL INSERT allows this.
    • If so, it should still be kept distinct from #27333, which would be a bulk import mechanism suitable for a large number of rows (different mechanism).
    • As alternatives, note that it's still possible to use the change tracker to insert multiple rows. #10879 would also allow bundling an arbitrary set of query or ExecuteXXX operations in a single batch.
  • Note that unlike ExecuteUpdate/Delete, ExecuteInsert doesn't need to return the number of rows affected (inserts either succeed or error), so the simple ExecuteInsert would return void/Task.
  • Similar to ExecuteUpdate and ExecuteDelete, since ExecuteInsert bypasses change tracking, it would also not (by default) fetch back database-generated values.
  • #29898 tracks adding RETURNING/OUTPUT support to ExecuteUpdate/Delete, which would be relevant here too. So some version of ExecuteInsert would return an IQueryable:
var dbGeneratedStuff = ctx.Blogs.ExecuteInsertReturning(blogs).Select(b => new { b.Id, b.Name}).ToArray();

At least in some DBs, returning an IQueryable allow embedding the insert in a CTE (WITH).

  • Consider whether we want to allow arbitrary expressions (e.g. INSERT INTO foo (bar) VALUES (current_timestamp)). This can also be useful to call some database function over a user-provided parameter (e.g. PG full-text search insertion, How to manually update a tsvector column? npgsql/efcore.pg#2317 (comment)). Note that there wouldn't be any query root here; only totally static functions make sense in this context. This also may intersect with server-side value converters (Support server side value conversions #10861), where a database function needs to be called on user-supplied data before inserting.

Activity

  1. added this to the Backlog milestone on Dec 21, 2022
  2. wdhenrik commented on Dec 22, 2022

    @wdhenrik

    I need to perform a Insert based on the result of a Select statement. The Insert needs to be associated with the first record returned in the Select statement and use the contents of the record to populate columns in the Insert.

    For example, this SQL query would set the Work.Status to In Progress of the first job with a Work.Status of New.

    DECLARE @InsertStatus VARCHAR(50) = 'In Progress';
    INSERT INTO dbo.Work (JobId,@InsertStatus)
    SELECT TOP 1 JobId FROM dbo.Work WHERE Status = 'New';
    

    If the Select and Insert are decoupled, then the 'first' record may change between the Select and Insert, leading to concurrency issues.

    Is there any way to do this in EFC7?

  3. roji commented on Dec 22, 2022

    @roji
    Author
  4. StrangeWill commented on Apr 19, 2023

    @StrangeWill

    Ran into a strong need for this on generating bulk data -- for the time being I just used a context factory to get around the ever-growing state of the change tracker and the overhead induced by that (nasty workaround but works), I've learned on EF Core for doing some lighter ETL and data generation but for some hefty datasets the change tracker is the number 1 thing in the way of performance.

    Only thing I'm somewhat hesitant about is dropping the return row count from the API, but as mentioned I can't really think of a use case that isn't served fine another way, and no weird "gotchas" there (triggers? I forget if those will show an inflated insert count if they do additional work -- I mean shows how much I read that value back out anyway)

    As EF Core has continued to mature it has been exciting watching things that require third party tooling slip into the mainline lib like ExecuteDelete and ExecuteUpdate, this is another welcome addition to basically Making those third party libs no longer required. :D

  5. roji commented on Apr 19, 2023

    @roji
    MemberAuthor

    @StrangeWill thanks for the feedback. FWIW for bulk insert you're probably looking for #27333; this issue here would be able getting EF to send INSERTs, whereas #27333 would be about using e.g. SqlBulkCopy.

  6. Charlieface commented on Jun 21, 2023

    @Charlieface

    The primary benefit I see of this feature would be to do the equivalent of

    INSERT INTO Table1 (Column1, Column2)
    SELECT Column1, 'FixedValueHere'
    FROM Table2;
    

    There is no way to do this currently, and the alternatives mentioned do not allow selecting from an existing table directly on the server. SqlBulkCopy needs the data to come back to the client, likewise even with the EFCore.BulkExtensions project.

    So you would do something like what we already have for ExecuteUpdate

    context.Table2
      .ExecuteInsert(setters => setters
           .Set(t1 => t1.Column1, t2 => t2.Column1)
           .Set(t1 => t1.Column2, t2 => "FixedValueHere")
      )
    

    to get the same result.

  7. roji commented on Jun 21, 2023

    @roji
    MemberAuthor

    @Charlieface INSERT ... SELECT ... is tracked by #27320, not by this issue, since you're fundamentally copying data between tables rather than from the client. And yes, when #27320 is implemented, it should allow you to generate the INSERT you wrote above.

  8. iXab3r commented on Dec 21, 2023

    @iXab3r
  9. roji commented on Dec 21, 2023

    @roji
    Author
  10. added theissue type on Jun 15, 2025
  11. radmorecameron commented on Feb 11, 2026

    @radmorecameron

    This would also be quite useful for seeding test data for keyless entities (ex: when using sqlite in-memory db for tests https://learn.microsoft.com/en-us/ef/core/testing/testing-without-the-database#sqlite-in-memory )

  12. AndriySvyryd commented on Nov 25, 2026

    @AndriySvyryd
    Member

    ExecuteInsert / ExecuteInsertReturning - design

    1. Goals and boundaries

    Insert one or more client-provided rows without the change tracker, optionally updating or ignoring matching rows on providers with native INSERT-based upsert. Optionally project database-generated and other target values.

    • ExecuteInsert modifies through SQL INSERT, with a native conflict clause where supported. It never uses MERGE or disguises a MERGE requirement as an insert optimization. Merge translation is tracked by Single-table ExecuteMerge #4526
    • Without .Match, perform a plain insert. A uniqueness violation is an error, not implicit upsert.
    • With .Match, use supported native upsert/conflict handling. SQL Server and other providers that cannot implement this without MERGE throw when translating .Match, even if the configured action would only ignore conflicts.
    • No graph traversal, change tracking, propagation of generated values into source entities, or automatic concurrency-token checks. Explicit token comparisons in a supported update condition remain possible.
    • This is not a specialized high-volume import API such as SqlBulkCopy (#27333). Parameterized multi-row inserts and batching are still supported.
    • An EF query source / INSERT ... SELECT remains separate work under #27320, as clarified in the issue comments. Do not fetch query results to the client as an implicit implementation.

    2. Public API

    Entry points

    Use the same target/source separation, nested configuration, and returning-selector shape as the simple ExecuteMerge overloads.

    int ExecuteInsert<TTarget, TSource>(
        this DbSet<TTarget> target,
        IEnumerable<TSource> source,
        Action<InsertBuilder<TTarget, TSource>>? buildInsert = null)
        where TTarget : class;
    
    Task<int> ExecuteInsertAsync<TTarget, TSource>(
        this DbSet<TTarget> target,
        IEnumerable<TSource> source,
        Action<InsertBuilder<TTarget, TSource>>? buildInsert = null,
        CancellationToken cancellationToken = default)
        where TTarget : class;
    
    IEnumerable<TResult> ExecuteInsertReturning<TTarget, TSource, TResult>(
        this DbSet<TTarget> target,
        IEnumerable<TSource> source,
        Action<InsertBuilder<TTarget, TSource>>? buildInsert,
        Expression<Func<TTarget, TResult>> returning)
        where TTarget : class;
    
    IAsyncEnumerable<TResult> ExecuteInsertReturningAsync<TTarget, TSource, TResult>(
        this DbSet<TTarget> target,
        IEnumerable<TSource> source,
        Action<InsertBuilder<TTarget, TSource>>? buildInsert,
        Expression<Func<TTarget, TResult>> returning,
        CancellationToken cancellationToken = default)
        where TTarget : class;
    
    IEnumerable<TResult> ExecuteInsertReturning<TTarget, TSource, TResult>(
        this DbSet<TTarget> target,
        IEnumerable<TSource> source,
        Action<InsertBuilder<TTarget, TSource>> buildInsert,
        Expression<Func<TTarget?, TTarget?, ModificationAction, TResult>> returning)
        where TTarget : class;
    
    IAsyncEnumerable<TResult> ExecuteInsertReturningAsync<TTarget, TSource, TResult>(
        this DbSet<TTarget> target,
        IEnumerable<TSource> source,
        Action<InsertBuilder<TTarget, TSource>> buildInsert,
        Expression<Func<TTarget?, TTarget?, ModificationAction, TResult>> returning,
        CancellationToken cancellationToken = default)
        where TTarget : class;

    Insert builder

    public class InsertBuilder<TTarget, TSource> where TTarget : class
    {
        InsertBuilder<TTarget, TSource> Match<TKey>(
            Expression<Func<TTarget, TKey>> targetKey,
            Expression<Func<TSource, TKey>> sourceKey);
    
        InsertBuilder<TTarget, TSource> WhenMatched(
            Action<InsertMatchedBuilder<TTarget, TSource>> buildAction,
            Expression<Func<TTarget, TSource, bool>>? condition = null);
    
        InsertBuilder<TTarget, TSource> WhenNotMatched(
            Action<InsertNotMatchedBuilder<TTarget, TSource>> setPropertyCalls);
    
        InsertBuilder<TTarget, TSource> PreserveSourceOrder();
    }
    
    public sealed class InsertMatchedBuilder<TTarget, TSource> where TTarget : class
    {
        InsertMatchedBuilder<TTarget, TSource> SetProperty<TProperty>(
            Expression<Func<TTarget, TProperty>> propertyExpression,
            Expression<Func<TTarget, TSource, TProperty>> valueExpression);
    
        InsertMatchedBuilder<TTarget, TSource> SetProperty<TProperty>(
            Expression<Func<TTarget, TProperty>> propertyExpression,
            TProperty valueExpression);
    
        InsertMatchedBuilder<TTarget, TSource> Where(
            Expression<Func<TTarget, TSource, bool>> condition);
    }
    
    public sealed class InsertNotMatchedBuilder<TTarget, TSource> where TTarget : class
    {
        InsertNotMatchedBuilder<TTarget, TSource> SetProperty<TProperty>(
            Expression<Func<TTarget, TProperty>> propertyExpression,
            Expression<Func<TSource, TProperty>> valueExpression);
    
        InsertNotMatchedBuilder<TTarget, TSource> SetProperty<TProperty>(
            Expression<Func<TTarget, TProperty>> propertyExpression,
            TProperty valueExpression);
    }

    3. Usage

    Plain insertion

    await context.Blogs.ExecuteInsertAsync(blogs, cancellationToken);

    Explicit values from a DTO and a server expression

    await context.Blogs.ExecuteInsertAsync(
        blogRows,
        insert => insert.WhenNotMatched(i => i
            .SetProperty(t => t.Name, s => s.DisplayName)
            .SetProperty(t => EF.Property<DateTime>(t, "CreatedAt"), s => DateTime.UtcNow)),
        cancellationToken);

    Insert or update on a selected conflict key

    var affected = await context.Products.ExecuteInsertAsync(
        productRows,
        insert => insert
            .Match(t => t.Sku, s => s.Sku)
            .WhenNotMatched(i => i
                .SetProperty(t => t.Sku, s => s.Sku)
                .SetProperty(t => t.Price, s => s.Price))
            .WhenMatched(u => u
                .SetProperty(t => t.Price, (t, s) => s.Price)),
        cancellationToken);

    SQLite/PostgreSQL can implement this with ON CONFLICT. SQL Server throws because .Match would require MERGE.

    Ignore matched rows and return inserted identities

    await foreach (var row in context.Products.ExecuteInsertReturningAsync(
        productRows,
        insert => insert
            .Match(t => t.Sku, s => s.Sku)
            .WhenMatched(u => u.DoNothing()),
        t => new { t.Id, t.Sku },
        cancellationToken))
    {
        // Only successfully inserted rows are returned.
    }

    Skipping a conflict can leave gaps relative to the source. It must not produce an existing target row or a default-value placeholder.

    4. SQL and provider capabilities

    Provider Plain INSERT With Match Returning
    SQLite Parameterized INSERT ... VALUES ON CONFLICT (columns) DO NOTHING or DO UPDATE SET ... [WHERE ...] (SQLite 3.24+) Target projection with RETURNING on 3.35+; obey the table's returning setting. Both inserted and updated rows are returned; ignored conflicts are not.
    PostgreSQL Parameterized INSERT ... VALUES ON CONFLICT (columns) DO NOTHING or DO UPDATE SET ... [WHERE ...] Target projection with RETURNING; both inserted and updated rows, not skipped conflicts.
    SQL Server Parameterized INSERT ... VALUES; never MERGE, including for generated-value correlation Throw before execution, including explicit do-nothing conflict handling OUTPUT inserted..., or capture with INSERT ... OUTPUT INTO and select captured output where needed.
    MySQL Parameterized INSERT ... VALUES Native ON DUPLICATE KEY UPDATE exists, but cannot select a conflict arbiter. Expose Match only for configurations where the provider can guarantee the declared key semantics; otherwise throw. No general MySQL INSERT RETURNING. A correct capture/readback strategy is required; otherwise throw for returning. Do not conflate MariaDB capabilities with MySQL.
    Other providers Opt in to native INSERT and supported output Throw unless native INSERT-based conflict handling satisfies this API without MERGE Provider capability check; no blanket claim of support.
    Cosmos / InMemory Not covered by this relational design Not covered Not covered

    Conflict semantics

    Match identifies the requested uniqueness conflict, not an arbitrary join predicate.

    • On SQLite/PostgreSQL, the target columns must have a matching PK/unique arbiter. A conflict on an unrelated key remains an error. Warn when the conflict columns do not match the PK, per the earlier design decision, but do not suppress a database error for a missing arbiter.
    • Match source values must agree with the values actually proposed for the corresponding insert columns. Otherwise ON CONFLICT would resolve a different key from the declared one.
    • On conflict-update paths, excluded/EXCLUDED describes the proposed insert row, not an unrestricted source relation. Reject source-member references that cannot be represented faithfully; do not silently substitute a differently converted or computed insert value.
    • MySQL's conflict detection applies to any unique key and can select a target not identified by the declared Match.
    • An explicit token-comparison update condition is allowed on providers that support it. EF adds no automatic token predicate and does not automatically interpret a skipped update as a concurrency exception.
    • Duplicate source-key semantics remain provider-specific. The provider behavior table owns the full description: SQLite can repeatedly upsert the same key; PostgreSQL DO UPDATE rejects affecting the same row twice in one statement; MySQL can repeatedly update and also has any-unique-key ambiguity. Plain inserts instead obey database uniqueness constraints. EF neither deduplicates nor promises first/last wins, and batching can change the statement-level outcome.

    Source and execution

    Reuse shared parameterized VALUES, batching, provider alternative transports, transaction/retry handling, and expression/mapping infrastructure. SQL Server's INSERT row-constructor limits apply in addition to its parameter limit; an INSERT-compatible source shape or smaller batches are required, not MERGE.

    An empty local source performs no insert and returns count zero / an empty result. It cannot have a target-only effect because this API has no such clauses. A null source is an argument error. Do not enumerate an EF database query as though it were a local collection.

    5. Returning semantics

    • The portable API projects from the new TTarget image for inserted and updated rows. Existing unchanged rows are never returned.
    • Do not add old/new/action selectors to this initial ExecuteInsert surface. Of the providers above, PostgreSQL 18 offers meaningful previous values for an INSERT conflict-update directly; SQL Server's plain INSERT can only produce an absent old image and an always-inserted action, and SQLite does not provide equivalent old/action output. The general MERGE overload is not copied merely to expose a single-provider upsert capability. Shared output infrastructure can still be reused.
    • In particular, omit PG 19 DO SELECT, row-lock modes, returnUnchanged, row-selection flags, and provider-specific action detection tricks from the portable API.
    • Return inserted and updated rows where a configured upsert performs both; do not claim support while returning only one action. A workaround must identify the rows actually changed, not indiscriminately reselect every source key.
    • SQL Server OUTPUT and SQLite/PostgreSQL RETURNING do not by themselves establish an order. Generated identities alone are insufficient correlation, particularly with skipped conflicts, triggers, or duplicate keys. Therefor results don't follow source order by default.
    • Project only the requested values plus any internal correlation data. Database-generated values are exposed in results, not assigned to the source objects.
    • The result is deferred and re-enumerating it re-executes the insert. It may stream where possible, but ordering/retries/provider capture can require buffering.
    • Unsupported returning configurations throw before making changes unless a correct native-INSERT-based capture/readback implementation is available. Plain INSERT remains usable even if that provider lacks returning.

    6. work checklist

    See the shared tasks in #4526 (comment)

    ExecuteInsert-specific remaining work

    • Introduce the ExecuteInsert entry points and nested builders.
    • Add independent INSERT/conflict SQL representation and translator entry points; do not implement these by calling ExecuteMerge. Connect them to the shared infrastructure rather than copying the old implementation.
    • Add INSERT-specific command-source integration and provider baselines/capability cases.
    • (@SkyDevLab) Implement PostgreSQL native INSERT/conflict translation for the portable subset, without adding PG-only returning/lock options.
    • Implement SQL Server plain INSERT/OUTPUT and throw fort every configuration containing Match.
    • Implement Cosmos support via UpsertItemAsync, requiring match on id and partition key and allowing to specify ETag as a filter.
    • Determine the safe subset, if any, for MySQL native conflict handling; reject unsupported key/action/condition/count/returning combinations rather than weakening semantics.
    • Cover insert-only distinctions: no implicit PK match, keyless writable targets, default-only rows, WhenMatched-without-Match rejection, no insert-suppression/delete/target-only methods, and unchanged-conflict exclusion.
  13. modified the milestones: Backlog, 12.0.0 on Nov 25, 2026
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