Repository navigation
Open
Milestone
Description
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:
- Ease-of-use. For the common task of adding a single entity, this would be a single line instead of two.
- 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.
Reacted by wdhenrik, Moritz Rinow, J, Roman Badiornyi, Ivan Bangiev, fenzel, VictorHumanist, Thomas Due, Henrik Elkjær Hagen, Martin Zima and 102 more
Reacted by J, VictorHumanist, Thomas Due, William Roush, Kent Kostelac, nra, Anže Videnič, icguy, Miguel Oliveira, Randy Reitz and 10 more
Activity
wdhenrik commentedon Dec 22, 2022
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.
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?
roji commentedon Dec 22, 2022
StrangeWill commentedon Apr 19, 2023
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
ExecuteDeleteandExecuteUpdate, this is another welcome addition to basically Making those third party libs no longer required. :Droji commentedon Apr 19, 2023
@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.
Charlieface commentedon Jun 21, 2023
The primary benefit I see of this feature would be to do the equivalent of
There is no way to do this currently, and the alternatives mentioned do not allow selecting from an existing table directly on the server.
SqlBulkCopyneeds 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
ExecuteUpdateto get the same result.
roji commentedon Jun 21, 2023
@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.iXab3r commentedon Dec 21, 2023
roji commentedon Dec 21, 2023
radmorecameron commentedon Feb 11, 2026
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 )
AndriySvyryd commentedon Nov 25, 2026
ExecuteInsert/ExecuteInsertReturning- design1. 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.
ExecuteInsertmodifies through SQLINSERT, with a native conflict clause where supported. It never usesMERGEor disguises a MERGE requirement as an insert optimization. Merge translation is tracked by Single-table ExecuteMerge #4526.Match, perform a plain insert. A uniqueness violation is an error, not implicit upsert..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.SqlBulkCopy(#27333). Parameterized multi-row inserts and batching are still supported.INSERT ... SELECTremains 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
ExecuteMergeoverloads.Insert builder
3. Usage
Plain insertion
Explicit values from a DTO and a server expression
Insert or update on a selected conflict key
SQLite/PostgreSQL can implement this with
ON CONFLICT. SQL Server throws because.Matchwould require MERGE.Ignore matched rows and return inserted identities
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
INSERT ... VALUESON CONFLICT (columns) DO NOTHINGorDO UPDATE SET ... [WHERE ...](SQLite 3.24+)RETURNINGon 3.35+; obey the table's returning setting. Both inserted and updated rows are returned; ignored conflicts are not.INSERT ... VALUESON CONFLICT (columns) DO NOTHINGorDO UPDATE SET ... [WHERE ...]RETURNING; both inserted and updated rows, not skipped conflicts.INSERT ... VALUES; never MERGE, including for generated-value correlationOUTPUT inserted..., or capture withINSERT ... OUTPUT INTOand select captured output where needed.INSERT ... VALUESON DUPLICATE KEY UPDATEexists, but cannot select a conflict arbiter. Expose Match only for configurations where the provider can guarantee the declared key semantics; otherwise throw.INSERT RETURNING. A correct capture/readback strategy is required; otherwise throw for returning. Do not conflate MariaDB capabilities with MySQL.Conflict semantics
Matchidentifies the requested uniqueness conflict, not an arbitrary join predicate.ON CONFLICTwould resolve a different key from the declared one.excluded/EXCLUDEDdescribes 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.DO UPDATErejects 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
TTargetimage for inserted and updated rows. Existing unchanged rows are never returned.DO SELECT, row-lock modes,returnUnchanged, row-selection flags, and provider-specific action detection tricks from the portable API.6. work checklist
See the shared tasks in #4526 (comment)
ExecuteInsert-specific remaining work
UpsertItemAsync, requiring match on id and partition key and allowing to specify ETag as a filter.