You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
Reacted by Andrey Taran, ivankarpey, DMW007, Tanguy Krotoff, Michael Khryashchev, Yosbel Esperón González, PeteX, Ryan Elian, Oleg Shevchenko, Andrey Denisov and 743 more
Reacted by Jefferson Santos, Sarah, doanhieu9797, Moaz Alkharfan, Arch0rr, Shine, Connor Hallman, Huu Hai and ZzZombo
Reacted by Timo van Zijll Langhout, Adam Bajguz, Jan Paolo Go, A.J. Ruckman, Doron Grinzaig, Michael, xzxzxc, Efe Burak, wangqiangqiang, Mario Henrique Lopes Duarte and 16 more
A set-based operator that inserts, updates and/or deletes target rows based on whether they match the source, without passing through the change tracker. It optionally returns target row values and the action performed.
Graph traversal or store-generated value propagation into tracked entities.
EF does will not add concurrency-token predicates. Callers can explicitly compare target/source tokens in a clause condition and inspect the affected count or returned results. Concurrency tokens themselves are not …
@NickAb I'm not sure Merge is even applicable to ORMs.
Can you write a little snippet showing how you would have use it?
Reacted by Cristian Eriomenco, Arad Alvand, Nenad Vićentić, Amr, Emil Tang Kristensen, alvinmaottd, tombohub, Mauricio Scheffer, Jay Chu, Erik O'Leary and 14 more
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.
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.
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)
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.
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)
Reacted by john, soleil, Chance Snow, Bruno Garcia, Josh DeGraw, cocowalla, Tanvir Ahmad Arjel, guopenglun, Khalil Mohammad Mirza, Jason Wisener and 25 more
@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.
Reacted by Michael Freidgeim, Alex Zaytsev, Jeremy, Yosbel Esperón González, soleil, Timo van Zijll Langhout and kewinbrand
@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.
@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:
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
Activity
gdoron commentedon Feb 11, 2016
@NickAb I'm not sure Merge is even applicable to ORMs.
Can you write a little snippet showing how you would have use it?
[-]Is there MERGE/UPSERT support in EF7?[/-][+]Merge/Upsert/AddOrUpdate support[/+]rowanmiller commentedon Feb 12, 2016
There isn't anything at the moment, though we could potentially do something nice (but not for 1.0.0).
NickAb commentedon Feb 13, 2016
@gdoron Actually, I am only interested in merge-as-upsert analog (upsert as in mongo upsert), not full-blown
MERGEsyntax, so it might look like:which will insert
newFeatureForRegionSettingif 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
MERGEuses.philn5d commentedon Mar 15, 2016
Is it the same feature as this?
NickAb commentedon Mar 15, 2016
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
philn5d commentedon Mar 15, 2016
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.
Ciantic commentedon Oct 4, 2016
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)
yosbeleg89 commentedon Mar 16, 2017
This is an implementation of MERGE to MSSQL than can give ideas. It is an extension method to EF6.
PeteX commentedon Apr 30, 2017
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:
roji commentedon Nov 24, 2017
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)
ajcvickers commentedon Nov 27, 2017
@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.
vovikdrg commentedon Jan 3, 2018
@ajcvickers https://docs.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql it seems to be "upsert"
137 remaining items
aromaa commentedon Nov 16, 2026
How would you express this with the proposed APIs?
Atulin commentedon Nov 16, 2026
¯\_(ツ)_/¯
AndriySvyryd commentedon Nov 17, 2026
We could add a more general Returning overload:
Usage:
Providers that don't support particular combinations would throw.
omri-klein-semperis commentedon Nov 22, 2026
@AndriySvyryd Thanks, looks good overall. A few comments:
1. Goals
WhenNotMatchedBySourceDelete. Maybe something like "inserts, updates and/or deletes target rows based on whether they match the source".WhenMatched(..., condition)in §5. Maybe say no automatic concurrency token checks, but users can still write the check as a condition.SaveChanges-basedAddOrUpdateand link it here?2. API
WhenNotMatched(_ => { })means "no insert", which is the opposite of leaving it out ("insert everything"). That's easy to get wrong. How about a separateWhenNotMatchedDoNothing()for update-only merge, and throwing on an emptyWhenNotMatched?(oldRow, newRow, action)+ReturningRowsoverload as the end goal, since it covers the simple one. Thet => ...overload can stay as a shortcut.4.
5.
WhenNotMatchedDoNothing()) first, then operators/functions inWhenMatchedvalues. I'm not planning to work on SQL Server or the other providers currently.[-]Merge/Upsert/AddOrUpdate support[/-][+]Single-table ExecuteMerge[/+]AndriySvyryd commentedon Nov 26, 2026
@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:
ExecuteMerge(implemented viaMERGE, this issue) andExecuteInsert(implemented viaINSERT, Non-tracking ExecuteInsert #29897). SaveChanges approach tracked by Add support for AddOrUpdate (Upsert via SaveChanges) #39800DbSet<>instead ofIQueryable<>Wheremethods instead ofconditionparametersDoNothingandDeletemethodsTSourceis different fromTTargetEF will try to match properties by name to avoid forcing users to callSetPropertyfor each, but will throw if any property is missingExecuteMergeReturningoverload will provide access to source properties to allow manual correlation and client-side orderingReturningRowsas most combinations are only supported by very few databases and providers can use extension methods to expose this functionality