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
{{ message }}
Repository navigation
Add support for INSERT/UPDATE/DELETE or IGNORE / ON CONFLICT DO NOTHING #16949
I propose adding an API to indicate to EF Core that an insert (via Add or AddRange and variants) may fail. This is useful when adding data to a table that may already exist.
For instance, I have a program that collects analytics data from a source and inserts it all into a table. Some of these rows may be duplicates of previously inserted rows and so will fail unique constraints. These errors can be safely ignored since the rows already exist in the table.
Using individual INSERT IGNORE ... statements results in horrible performance (~15x slower than AddRangeAsync).
Reacted by Timo van Zijll Langhout, José Carlos, Melvyn Laïly, leoshusar, janaKaszyda, mojtaba kaviani, Oleksandr Popov, Rowan, David Faivre, Will Nations and 52 more
EF Team Triage: This issue is not something that our team is planning to address in the EF6.x code base. This does not mean that we would not consider a community contribution to address this issue.
Closing an issue in the EF6.x project does not exclude us addressing it in EF Core. In fact, a number of popular feature requests for EF have already been implemented in EF Core (alternate keys, batching in SaveChanges, etc.).
BTW this is a canned response and may have info or details that do not directly apply to this particular issue. While we'd like to spend the time to uniquely address every incoming issue, we get a lot traffic on the EF projects and that is not practical. To ensure we maximize the time we have to work on fixing bugs, implementing new features, etc. we use canned responses for common triage decisions.
@ajcvickers Oh I see. I don't know which repo hosts the EF6 code base, but since this one is already the EF Core code base, can we leave the issue open?
Notes from triage: it's not 100% clear that this is really useful in the context of an OR/M, but moving it to the backlog to consider at a later time.
At least for MySql, it's very useful.
I‘ve seen a lot of questions like INSERT-IGNORE-using-EF-Core about how to insert datas into a table , which already has datas and an unique index/key, without any exceptions(if the data exists, just skip it). MySql supports it by 'insert ignore into', while SqlServer is still unknown to me for the answer.
If EF Core provides the API, we'll get the best practice.
I also think this is a very important feature that even most basic app needs.
Consider a scenario where there is a 3rd-party data provider, and I can only query last N objects, that I later transform and insert in my db. Without this functionality I need to first check which object already exists by first querying the db, excluding the existing id, and only inserting the new ones.
Note #14464 which was about using the following technique to achieve "add or ignore":
INSERT INTO Users (UserName, Email)
SELECT @UserName, @Email
EXCEPT
SELECT UserName, Email
FROM Users
WHERE Email = @Email
On databases where a specific syntax already exists for add or ignore, that's obviously best. On SQL Server - where no such thing exists - the above could be an alternative implementation. Another way to approach this would be with MERGE - which may be more efficient - though MERGE would probably have concurrency issues (all this needs to be researched).
If we want Insert only new and skip existing ones in Db (Insert_if_not_Exist) then use BulkInsertOrUpdate with config PropertiesToIncludeOnUpdate = new List<string> { "" }
Disc. I'm the author, and Lib. now has Dual License - cFOSS as a fix for OSS sustainability.
(Community version is free and covers most users, Commercial one is for companies over 1 mil. revenue)
I would really like to see something like this supported in EF Core.
My specific use-case: I'm writing a (simple) data importer which periodically imports CSV data into my application database. The data being imported in each CSV is relatively small, but the operation happens often enough that the database is expected to be very large over time, and the operation may run in parallel with other imports. Since the data in the database only comes from the same source, it's never an issue if a new record can't be added (because its primary key is already in the table); in fact it's very likely since the CSV data deliberately contains an hour or so of overlapping data each import to avoid missing records added around the time of export.
On SQL Server this can be achieved with the IGNORE_DUP_KEY argument on the index, but using that throws exceptions in EF Core, presumably because of entity change tracking. I'm sure you're already familiar with this property, but I struggled to find this issue again because none of the other comments mention that specific argument by name.
@kitgrose on SQL Server, this kind of thing is typically achieved via the MERGE statement, which is presumably what we'd use to implement the future insert-or-ignore API. For now, you should be able to drop down to SQL to code this specific importer.
Does not handle a real concurrency issue.
It does an INSERT ... WHERE NOT EXISTS ... which is very different than a ON CONFLICT DO ...
In transaction mode, if two transaction with the same insert are committed it will fail.
@roji I have to agree with @kitgrose here. My use case is receiving event messages each with a GUID. 99% of the time these insert straight into our SQL Server table, so I absolutely do not want to check for existence before trying to save each one. But during deployments, the receiving Azure Function is interrupted and the Azure Event Hub begins re-sending large numbers of messages. We currently have try-catches in place to swallow duplicate exceptions, but this is not as performant as letting the database swallow the duplicate. And even catching the exception, EF still finds a way to push these duplicate messages out to the console making for an awful lot of red.
As with kitgrose, if I change the database unique index to use SQL Server's IGNORE_DUP_KEY, EF chokes on the save with "Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: The database operation was expected to affect 1 row(s)..." Would you think it better if EF was configurable to ignore DbUpdateConcurrencyExceptions during a given SaveChangesAsync?
Also, one of the main reasons our team adopted EF was for its ability to mock a database in memory. We use this heavily for a now large bank of automated tests which is baked into the Azure DevOps build pipeline. The EF in-memory database does not support SQL (and I get it - which provider would it use?), so "dropping down to SQL" is unfortunately not an option for me.
Thanks!
We currently have try-catches in place to swallow duplicate exceptions, but this is not as performant as letting the database swallow the duplicate.
As a general rule, unless you're constantly getting lots of duplicates, the performance impact should be negligible - is this something you've measured in your specific scenario? I'd recommend not assuming in advance that the try/catch strategy is problematic perf-wise unless you have a clear indication that it is.
And even catching the exception, EF still finds a way to push these duplicate messages out to the console making for an awful lot of red.
This is something you can suppress.
Also, one of the main reasons our team adopted EF was for its ability to mock a database in memory. We use this heavily for a now large bank of automated tests which is baked into the Azure DevOps build pipeline. The EF in-memory database does not support SQL (and I get it - which provider would it use?), so "dropping down to SQL" is unfortunately not an option for me.
This is specifically something we discourage, and we've generally stopped investing in the in-memory provider. You're saying here that you don't want to do something in production because your testing approach is somehow incomaptible with it; this is an odd situation, and should indicate that the testing approach is problematic - testing constraints should not guide/determine production.
Take a look at our testing docs. In a nutshell, in 2026, simply testing against SQL Server (likely using containers/testcontainers) is the strategy I'd advise by default, unless there are very specific reasons to not do so. This guarantees full-fidelity testing, whereas when testing against an in-memory mock database your test may pass in testing and fail in production. There is a vast number of behavioral differences - small and large - between how the in-memory database and your real SQL Server database will behave, and you generally don't want that for a robust testing approach.
Regardless of all of the above... We do indeed believe that EF should do better here; EF should support insert-or-update (upsert) or insert-or-ignore. This issue is open for tracking that, but it's quite a non-trivial thing to do, and we haven't had sufficient resources to tackle it, given other priorities. We also need to do this in a way which makes sense for each database, and can't rely on a SQL Server-specific feature (e.g. IGNORE_DUP_KEY ). In the meantime you'll unfortunately have to make do with the existing means, like try/catch.
changed the title [-]Add support for INSERT IGNORE / ON CONFLICT DO NOTHING[/-][+]Add support for INSERT/UPDATE/DELETE or IGNORE / ON CONFLICT DO NOTHING[/+]on Nov 25, 2026
Activity
ErikEJ commentedon Aug 5, 2019
What Database provider?
ajcvickers commentedon Aug 5, 2019
EF Team Triage: This issue is not something that our team is planning to address in the EF6.x code base. This does not mean that we would not consider a community contribution to address this issue.
Moving forwards, our team will be fixing bugs, implementing small improvements, and accepting community contributions to the EF6.x code base. Larger feature work and innovation will happen in the EF Core code base (https://github.com/aspnet/EntityFramework).
Closing an issue in the EF6.x project does not exclude us addressing it in EF Core. In fact, a number of popular feature requests for EF have already been implemented in EF Core (alternate keys, batching in SaveChanges, etc.).
BTW this is a canned response and may have info or details that do not directly apply to this particular issue. While we'd like to spend the time to uniquely address every incoming issue, we get a lot traffic on the EF projects and that is not practical. To ensure we maximize the time we have to work on fixing bugs, implementing new features, etc. we use canned responses for common triage decisions.
shravan2x commentedon Aug 5, 2019
@ErikEJ MySql.Data and MySqlConnector (I tested on both).
@ajcvickers Isn't this already the EF Core repo? I'm confused what you mean by your comment.
ajcvickers commentedon Aug 5, 2019
@shravan2x It's a boilerplate message--see the note at the end of it. The point is we're not going to do it for EF6.
shravan2x commentedon Aug 5, 2019
@ajcvickers Oh I see. I don't know which repo hosts the EF6 code base, but since this one is already the EF Core code base, can we leave the issue open?
EDIT: Hopefully I understood what you meant :)
ajcvickers commentedon Aug 5, 2019
@shravan2x Are you asking for this to be implemented in EF Core or EF6?
shravan2x commentedon Aug 5, 2019
@ajcvickers EF Core. Sorry, my original question was mis-worded. I'll fix that.
ajcvickers commentedon Aug 5, 2019
@shravan2x We will discuss in triage.
ajcvickers commentedon Aug 12, 2019
Notes from triage: it's not 100% clear that this is really useful in the context of an OR/M, but moving it to the backlog to consider at a later time.
LeaFrock commentedon Oct 28, 2019
At least for MySql, it's very useful.
I‘ve seen a lot of questions like INSERT-IGNORE-using-EF-Core about how to insert datas into a table , which already has datas and an unique index/key, without any exceptions(if the data exists, just skip it). MySql supports it by 'insert ignore into', while SqlServer is still unknown to me for the answer.
If EF Core provides the API, we'll get the best practice.
15 remaining items
roji commentedon Mar 22, 2022
Thanks @mqudsi, makes sense.
Note SqlServerIndexConvention, which is a SQL Server-specific convention that filters out NULLs on unique non-clustered indexes.
But let's continue any conversation on this in npgsql/efcore.pg#2298, as this is quite off-topic here.
dragoon commentedon Jul 12, 2022
I also think this is a very important feature that even most basic app needs.
Consider a scenario where there is a 3rd-party data provider, and I can only query last N objects, that I later transform and insert in my db. Without this functionality I need to first check which object already exists by first querying the db, excluding the existing id, and only inserting the new ones.
roji commentedon Oct 19, 2022
Note #14464 which was about using the following technique to achieve "add or ignore":
On databases where a specific syntax already exists for add or ignore, that's obviously best. On SQL Server - where no such thing exists - the above could be an alternative implementation. Another way to approach this would be with MERGE - which may be more efficient - though MERGE would probably have concurrency issues (all this needs to be researched).
borisdj commentedon May 8, 2023
To add one solution, using EFCore.BulkExtensions this can be done with
Disc. I'm the author, and Lib. now has Dual License - cFOSS as a fix for OSS sustainability.
(Community version is free and covers most users, Commercial one is for companies over 1 mil. revenue)
kitgrose commentedon May 15, 2024
I would really like to see something like this supported in EF Core.
My specific use-case: I'm writing a (simple) data importer which periodically imports CSV data into my application database. The data being imported in each CSV is relatively small, but the operation happens often enough that the database is expected to be very large over time, and the operation may run in parallel with other imports. Since the data in the database only comes from the same source, it's never an issue if a new record can't be added (because its primary key is already in the table); in fact it's very likely since the CSV data deliberately contains an hour or so of overlapping data each import to avoid missing records added around the time of export.
On SQL Server this can be achieved with the
IGNORE_DUP_KEYargument on the index, but using that throws exceptions in EF Core, presumably because of entity change tracking. I'm sure you're already familiar with this property, but I struggled to find this issue again because none of the other comments mention that specific argument by name.roji commentedon May 15, 2024
@kitgrose on SQL Server, this kind of thing is typically achieved via the MERGE statement, which is presumably what we'd use to implement the future insert-or-ignore API. For now, you should be able to drop down to SQL to code this specific importer.
jordinl commentedon Feb 10, 2025
roji commentedon Feb 10, 2025
kYann commentedon Jul 3, 2025
EFCore.BulkExtensions
Does not handle a real concurrency issue.
It does an INSERT ... WHERE NOT EXISTS ... which is very different than a ON CONFLICT DO ...
In transaction mode, if two transaction with the same insert are committed it will fail.
StarTrekRedneck commentedon Mar 25, 2026
@roji I have to agree with @kitgrose here. My use case is receiving event messages each with a GUID. 99% of the time these insert straight into our SQL Server table, so I absolutely do not want to check for existence before trying to save each one. But during deployments, the receiving Azure Function is interrupted and the Azure Event Hub begins re-sending large numbers of messages. We currently have try-catches in place to swallow duplicate exceptions, but this is not as performant as letting the database swallow the duplicate. And even catching the exception, EF still finds a way to push these duplicate messages out to the console making for an awful lot of red.
As with kitgrose, if I change the database unique index to use SQL Server's
IGNORE_DUP_KEY, EF chokes on the save with "Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: The database operation was expected to affect 1 row(s)..." Would you think it better if EF was configurable to ignore DbUpdateConcurrencyExceptions during a given SaveChangesAsync?Also, one of the main reasons our team adopted EF was for its ability to mock a database in memory. We use this heavily for a now large bank of automated tests which is baked into the Azure DevOps build pipeline. The EF in-memory database does not support SQL (and I get it - which provider would it use?), so "dropping down to SQL" is unfortunately not an option for me.
Thanks!
roji commentedon Mar 26, 2026
As a general rule, unless you're constantly getting lots of duplicates, the performance impact should be negligible - is this something you've measured in your specific scenario? I'd recommend not assuming in advance that the try/catch strategy is problematic perf-wise unless you have a clear indication that it is.
This is something you can suppress.
This is specifically something we discourage, and we've generally stopped investing in the in-memory provider. You're saying here that you don't want to do something in production because your testing approach is somehow incomaptible with it; this is an odd situation, and should indicate that the testing approach is problematic - testing constraints should not guide/determine production.
Take a look at our testing docs. In a nutshell, in 2026, simply testing against SQL Server (likely using containers/testcontainers) is the strategy I'd advise by default, unless there are very specific reasons to not do so. This guarantees full-fidelity testing, whereas when testing against an in-memory mock database your test may pass in testing and fail in production. There is a vast number of behavioral differences - small and large - between how the in-memory database and your real SQL Server database will behave, and you generally don't want that for a robust testing approach.
Regardless of all of the above... We do indeed believe that EF should do better here; EF should support insert-or-update (upsert) or insert-or-ignore. This issue is open for tracking that, but it's quite a non-trivial thing to do, and we haven't had sufficient resources to tackle it, given other priorities. We also need to do this in a way which makes sense for each database, and can't rely on a SQL Server-specific feature (e.g. IGNORE_DUP_KEY ). In the meantime you'll unfortunately have to make do with the existing means, like try/catch.
[-]Add support for INSERT IGNORE / ON CONFLICT DO NOTHING[/-][+]Add support for INSERT/UPDATE/DELETE or IGNORE / ON CONFLICT DO NOTHING[/+]