Skip to content

Single-table ExecuteMerge #4526

Open

Description

@NickAb

In my project I need to insert entity if it does not exist yet, or update it otherwise (somewhat like UPSERT in mongodb). As I understand in SQL it can be accomplished using MERGE, but I was not able to find MERGE in EF Core.

Pinned by AndriySvyryd

Activity

  1. gdoron commented on Feb 11, 2016

    @gdoron

    @NickAb I'm not sure Merge is even applicable to ORMs.
    Can you write a little snippet showing how you would have use it?

  2. changed the title [-]Is there MERGE/UPSERT support in EF7?[/-] [+]Merge/Upsert/AddOrUpdate support[/+] on Feb 12, 2016
  3. rowanmiller commented on Feb 12, 2016

    @rowanmiller
    Contributor

    There isn't anything at the moment, though we could potentially do something nice (but not for 1.0.0).

  4. added this to the Backlog milestone on Feb 12, 2016
  5. NickAb commented on Feb 13, 2016

    @NickAb
    Author

    @gdoron Actually, I am only interested in merge-as-upsert analog (upsert as in mongo upsert), not full-blown MERGE syntax, so it might look like:

    var newFeatureForRegionSetting = new FeatureForRegionSetting();
    entity.Region = region;
    entity.Feature = feature;
    entity.Settings = settings;
    
    dbCtx. FeatureForRegionSettings.Upsert(x => x.region == entity.region && x.feature == entity.feature, newFeatureForRegionSetting);

    which will insert newFeatureForRegionSetting if condition is not matched, or update entity if condition is matched.

    I can not provide usage example for full-blown merge, as I am not that familiar with other MERGE uses.

  6. philn5d commented on Mar 15, 2016

    @philn5d

    Is it the same feature as this?

  7. NickAb commented on Mar 15, 2016

    @NickAb
    Author

    No, I don't think so. As I understand, the issue you are referring to is about "merging disconnected graphs", so it is about interworking of EF change tracking, etc.
    What I am referring to is SQL MERGE statement, see docs here https://msdn.microsoft.com/en-us/library/bb510625.aspx

  8. philn5d commented on Mar 15, 2016

    @philn5d

    Ah, I've done this with a home brewed extension method but it needs to get the entity before doing the upsert. Needed to define the key value and didn't support multiple keys. Would be useful to have since it would be more performant.

    There's a pattern described https://msdn.microsoft.com/en-us/data/jj592676.aspx
    Which is essentially what I wrapped in the extension, would be much better if the framework did this instead. Especially if it can be made to determine if the keys are default or not - without necessarily loading the entity from the data store.

    Perhaps it could leverage the MERGE statement as you alluded to. Match on entity keys. I could see folks wanting the results of the MERGE returned which would complicate the operation. The simple case would be useful enough to warrant only Insert or Update with no additional complexity. Also, depends on whether or not the data store supports MERGE if its to be used to implement the feature.

  9. Ciantic commented on Oct 4, 2016

    @Ciantic

    There is a very handy document in PostgreSQL wiki about UPSERT in various SQL dialects. It may come handy if someone is trying to implement it in the EF.

    (In practice it seems there is no agreed way how it should work, especially with unique fields, and would be a messy thing to do in EF because of it)

  10. yosbeleg89 commented on Mar 16, 2017

    @yosbeleg89

    This is an implementation of MERGE to MSSQL than can give ideas. It is an extension method to EF6.

  11. PeteX commented on Apr 30, 2017

    @PeteX

    I know there are lots of things it would be nice to support, and limited developer time, but it's a shame this one is missing. Apart from this, my code is entirely database-independent, but it's hard to implement upsert without database support.

    The usual pattern is that you try to insert, and whether it succeeds or fails, you know the relevant row is in the database. You can therefore pull it out and work with it. There are problems with this approach, though:

    • As far as I can tell, you have to discard the DbContext after the insert fails, because otherwise the next SaveChanges() will retry the insert.
    • EF Core seems to write an unwanted exception message into the log when the insert fails.
    • Failure usually aborts transactions, so the insert attempt and the following update can't be atomic. This creates problems with races where the insert succeeds, but the row gets updated before the following update.
  12. roji commented on Nov 24, 2017

    @roji
    Member

    Just pinging this to make sure it's not totally forgotten. With the seemingly wide support of UPSERT/MERGE across databases, this could be a pretty valuable feature (although of course the specific implementations/variations would have to be investigated (see this comparative doc cited above by @Ciantic)

  13. ajcvickers commented on Nov 27, 2017

    @ajcvickers
    Contributor

    @roji Thanks--there's definitely a lot of value in doing this. the comparative doc is very useful--we would have to figure out what to do for SQL Server.

  14. vovikdrg commented on Jan 3, 2018

    @vovikdrg
  15. 137 remaining items

  16. aromaa commented on Nov 16, 2026

    @aromaa

    That's up to the Postgres provider

    How would you express this with the proposed APIs?

  17. Atulin commented on Nov 16, 2026

    @Atulin

    That's up to the Postgres provider

    How would you express this with the proposed APIs?

    ¯\_(ツ)_/¯

  18. AndriySvyryd commented on Nov 17, 2026

    @AndriySvyryd
    Member

    We could add a more general Returning overload:

    IEnumerable<TResult> ExecuteMergeReturning<TTarget, TSource, TResult>(
        this IQueryable<TTarget> target,
        IEnumerable<TSource> source,
        Action<MergeBuilder<TTarget, TSource>> buildMerge,
        Expression<Func<TTarget?, TTarget?, ModificationAction, TResult>> returning,
        ReturningRows rows = ReturningRows.Modified)
        where TTarget : class;
    
    public enum ModificationAction
    {
        Inserted,
        Updated,
        Deleted,
        Unchanged
    }
    
    [Flags]
    public enum ReturningRows
    {
        Inserted = 1,
        Updated = 2,
        Deleted = 4,
        Unchanged = 8,
    
        Modified = Inserted | Updated | Deleted,
        All = Modified | Unchanged
    }

    Usage:

    var results = context.Products.ExecuteMergeReturning(
        source,
        merge => merge
            .Match(t => t.Sku, s => s.Sku)
            .WhenMatched(update => update
                .SetProperty(t => t.Price, (t, s) => s.Price)),
        returning: (oldRow, newRow, action) => new
        {
            Action = action,
            Id = newRow != null ? newRow.Id : oldRow!.Id,
            PreviousPrice = oldRow == null ? (decimal?)null : oldRow.Price,
            CurrentPrice = newRow == null ? (decimal?)null : newRow.Price
        },
        rows: ReturningRows.All);

    Providers that don't support particular combinations would throw.

  19. pinned this issue on Nov 18, 2026
  20. unpinned this issue on Nov 18, 2026
  21. omri-klein-semperis commented on Nov 22, 2026

    @omri-klein-semperis
    Contributor

    @AndriySvyryd Thanks, looks good overall. A few comments:

    1. Goals

    • The goal only says insert + update/skip, but the API also has update-only merge and WhenNotMatchedBySourceDelete. Maybe something like "inserts, updates and/or deletes target rows based on whether they match the source".
    • "Concurrency tokens" as a non-goal reads a bit odd next to the optimistic concurrency example for WhenMatched(..., condition) in §5. Maybe say no automatic concurrency token checks, but users can still write the check as a condition.
    • This issue is titled Merge/Upsert/AddOrUpdate, but it now only tracks the bulk operator. Should we open a separate issue for the SaveChanges-based AddOrUpdate and link it here?

    2. API

    • An empty WhenNotMatched(_ => { }) means "no insert", which is the opposite of leaving it out ("insert everything"). That's easy to get wrong. How about a separate WhenNotMatchedDoNothing() for update-only merge, and throwing on an empty WhenNotMatched?
    • For RETURNING, I like your (oldRow, newRow, action) + ReturningRows overload as the end goal, since it covers the simple one. The t => ... overload can stay as a shortcut.

    4.

    • Duplicate match keys in the source aren't covered. PG and SQL Server error, while SQLite applies both rows. Once the source is split into batches, duplicates in different batches won't error anywhere. We should pick one behavior: throw, last row wins, or leave it to the provider and document it.

    5.

    • Please add @SkyDevLab to the PostgreSQL item in the checklist.
    • I'll take update-only merge (with WhenNotMatchedDoNothing()) first, then operators/functions in WhenMatched values. I'm not planning to work on SQL Server or the other providers currently.
  22. changed the title [-]Merge/Upsert/AddOrUpdate support[/-] [+]Single-table ExecuteMerge[/+] on Nov 25, 2026
  23. AndriySvyryd commented on Nov 26, 2026

    @AndriySvyryd
    Member

    @omri-klein-semperis Updated based on your remarks. We also had a team design discussion and made numerous additional changes, here are the biggest ones:

    • Separate ExecuteMerge (implemented via MERGE, this issue) and ExecuteInsert (implemented via INSERT, Non-tracking ExecuteInsert #29897). SaveChanges approach tracked by Add support for AddOrUpdate (Upsert via SaveChanges) #39800
    • The main methods will be defined on DbSet<> instead of IQueryable<>
    • Added nested Where methods instead of condition parameters
    • Also added nested DoNothing and Delete methods
    • When TSource is different from TTarget EF will try to match properties by name to avoid forcing users to call SetProperty for each, but will throw if any property is missing
    • No results ordering by default, the general ExecuteMergeReturning overload will provide access to source properties to allow manual correlation and client-side ordering
    • Removed ReturningRows as most combinations are only supported by very few databases and providers can use extension methods to expose this functionality
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