Skip to content

Return the rows of BulkInsertOrUpdate and BulkUpdate (SQL Server OUTPUT, PostgreSQL and SQLite RETURNING) - #81

Open
pengweiqhca wants to merge 7 commits into
PawelGerr:releases/10.0.xfrom
pengweiqhca:feat/bulk-operations-returning
Open

pengweiqhca wants to merge 7 commits into
PawelGerr:releases/10.0.xfrom
pengweiqhca:feat/bulk-operations-returning

Conversation

@pengweiqhca

Copy link
Copy Markdown
Contributor

Summary

BulkInsertOrUpdateAsync and BulkUpdateAsync can now return the rows they wrote, selected with a projection:

// provider independent: the row after the operation
var rows = await ctx.BulkInsertOrUpdateAsync(
   entities,
   options,
   row => new { row.Inserted.Id, row.Inserted.Count });

// SQL Server only: old values and the action of the MERGE statement
var rows = await ctx.BulkInsertOrUpdateAsync(
   entities,
   new SqlServerBulkInsertOrUpdateOptions(),
   row => new { row.Inserted.Id, OldCount = row.Deleted.Count, row.Action });

The result is a List<TResult> with one entry per inserted or updated row. The order is not defined and is not the order of entities. Only the properties that the projection reads are requested from the database, and values go through the value converters of the model. Properties that are not read keep their default values. The projection may read scalar properties that are mapped to a column of the table, or the whole row.Inserted; reading anything else throws NotSupportedException. The existing overloads that return the number of affected rows generate the same statements as before.

Providers

Provider Statement Available members
SQL Server MERGE ... OUTPUT ... INTO @table, then SELECT from the table variable Inserted, Deleted, Action (SqlServerMergeOutput<T>) or Inserted only (BulkOperationOutput<T>)
PostgreSQL RETURNING appended to INSERT ... ON CONFLICT and UPDATE ... FROM Inserted
SQLite RETURNING appended to the statement of each row Inserted
MySQL not supported, because the statements have no RETURNING/OUTPUT the overloads throw NotSupportedException

Notes:

  • SQL Server writes the rows into a table variable with OUTPUT ... INTO, because SQL Server rejects OUTPUT without INTO if the target table has enabled triggers. deleted columns of an inserted row are NULL, so nullable properties are null and the others keep their default value. Use Action to tell the cases apart.
  • The provider independent overload works on SQL Server as well. It reads Inserted only and is rewritten to the SqlServerMergeOutput<T> projection; using the output row as a whole (row => row) throws NotSupportedException. Because the overload is selected by the type of the options argument, code that passes SqlServerBulkInsertOrUpdateOptions gets Inserted, Deleted and Action.
  • SQLite returns the rows of the root entity only. A row that a conflict clause skips or an update that matches no row returns nothing. Rows of owned types that are stored in separate tables are not returned.
  • With ConflictDoNothing on PostgreSQL, RETURNING returns the inserted rows only, because skipped rows are not returned by PostgreSQL.

Implementation

  • BulkOperationOutput<T> and IBulkOperationOutputExecutor (BulkOperations) are the provider independent API. The DbContext extension methods resolve the executor from the service provider and throw NotSupportedException if the provider has none.
  • BulkOperationReturningProjection<T, TResult> translates the projection to column names and materializes the rows. PostgreSQL and SQLite use it.
  • SQL Server has its own plan (SqlServerMergeOutputPlan), because it also selects deleted.* and $action.
  • BulkOperationsSqlExecutor.ExecuteReaderAsync runs a library-built statement through the command pipeline of EF Core and passes the data reader to a callback. Logging, interceptors, the current transaction, the command timeout and the concurrency check apply, as for ExecuteNonQueryAsync.

Tests

  • SQL Server: MergeOutput (11 tests). Covers inserted/deleted values and Action, only the requested columns in the statement, the whole entity with value converter and private field, a table with an enabled trigger, BulkUpdate, a redirected table name, an empty input, and the provider independent overloads.
  • PostgreSQL and SQLite: BulkOperationOutputAsync (6 tests each).
  • The existing BulkOperations tests of PostgreSQL (320) and SQLite (354) pass. The SQL Server BulkOperations tests (272) passed before the last commit, which only adds the provider independent overload.

Not included: the wiki documentation.

…f a library-built statement

BulkOperationsSqlExecutor executes library-built statements through the command pipeline of EF Core without String.Format, but it could only run statements that return an affected-row count. ExecuteReaderAsync runs a statement the same way and passes the data reader to a callback, so statements that return rows, for example a MERGE with an OUTPUT clause, keep logging, interceptors, the current transaction, the command timeout and the concurrency check of the context. The reader is disposed after the callback returns.
…rtOrUpdate and BulkUpdate

DbContext.BulkInsertOrUpdateAsync and DbContext.BulkUpdateAsync have new overloads for SQL Server that take a projection of SqlServerMergeOutput<T> and return one result per inserted or updated row, for example row => new { row.Inserted.Id, OldName = row.Deleted.Name, row.Action }. Inserted maps to inserted.*, Deleted to deleted.* and Action to $action. Only the properties that the projection reads are requested, and values go through the value converters of the model. The properties of an entity that are not read keep their default values, and the deleted columns of an inserted row are NULL.

The rows are written into a table variable with OUTPUT ... INTO and selected afterwards, because SQL Server rejects an OUTPUT clause without INTO if the target table has enabled triggers. The existing overloads that return the number of affected rows generate the same statement as before. The order of the returned rows is not defined.
…greSQL and SQLite

DbContext.BulkInsertOrUpdateAsync and DbContext.BulkUpdateAsync have new overloads that take a projection of BulkOperationOutput<T> and return one result per inserted or updated row, for example row => new { row.Inserted.Id, row.Inserted.Name }. Inserted is the row after the operation. Only the properties that the projection reads are requested, and values go through the value converters of the model. The properties of an entity that are not read keep their default values.

The overloads are implemented by IBulkOperationOutputExecutor. PostgreSQL appends a RETURNING clause to the INSERT ... ON CONFLICT and the UPDATE ... FROM statements. SQLite appends it to the statement of each row and reads the returned row, so a row that a conflict clause skips or an update that matches no row returns nothing. SQLite returns only the rows of the root entity, rows of owned types that are stored in separate tables are not returned. The existing overloads that return the number of affected rows generate the same statements as before. The order of the returned rows is not defined.

BulkOperationReturningProjection translates the projection to the column names of the RETURNING clause and materializes the rows, so the providers share it.
…L Server

SqlServerBulkOperationExecutor implements IBulkOperationOutputExecutor, so DbContext.BulkInsertOrUpdateAsync and DbContext.BulkUpdateAsync with a BulkOperationOutput<T> projection also work on SQL Server, for example in code that only knows IBulkInsertOrUpdateOptions. The projection reads Inserted only. It is rewritten to the SqlServerMergeOutput<T> projection that the SQL Server specific overloads use, so both overloads generate the same OUTPUT clause. A projection that uses the output row as a whole, for example row => row, throws NotSupportedException, because the row has no SQL Server specific members to load.
Copilot AI balanced review requested due to automatic review settings December 3, 2026 10:06

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Critical materialization defects can throw after writes or return incorrect entity types and NULL values, while whole-entity projections bypass navigation validation.

6 open issues
What changed in this PR

Adds projected row results to the existing bulk upsert and update APIs for SQL Server, PostgreSQL, and SQLite.

Changes:

  • Introduces shared output APIs and SQL Server-specific inserted/deleted values and merge actions.
  • Adds OUTPUT/RETURNING execution and result materialization while preserving affected-row-count overloads.
  • Adds integration tests for projections, conversions, triggers, and provider-independent calls.
File Description
tests/​Thinktecture.EntityFrameworkCore.SqlServer.Tests/​EntityFrameworkCore/​BulkOperations/​SqlServerBulkOperationExecutorTests/​MergeOutput.cs Tests SQL Server output behavior.
tests/​Thinktecture.EntityFrameworkCore.Sqlite.Tests/​EntityFrameworkCore/​BulkOperations/​SqliteBulkOperationExecutorTests/​BulkOperationOutputAsync.cs Tests SQLite returned rows.
tests/​Thinktecture.EntityFrameworkCore.PostgreSQL.Tests/​EntityFrameworkCore/​BulkOperations/​NpgsqlBulkOperationExecutorTests/​BulkOperationOutputAsync.cs Tests PostgreSQL returned rows.
src/​Thinktecture.EntityFrameworkCore.SqlServer/​Extensions/​SqlServerMergeOutputDbContextExtensions.cs Exposes SQL Server output overloads.
src/​Thinktecture.EntityFrameworkCore.SqlServer/​EntityFrameworkCore/​Infrastructure/​SqlServerDbContextOptionsExtension.cs Registers the output executor.
src/​Thinktecture.EntityFrameworkCore.SqlServer/​EntityFrameworkCore/​BulkOperations/​SqlServerMergeOutputPlan.cs Builds and materializes merge output.
src/​Thinktecture.EntityFrameworkCore.SqlServer/​EntityFrameworkCore/​BulkOperations/​SqlServerMergeOutput.cs Defines inserted/deleted output rows.
src/​Thinktecture.EntityFrameworkCore.SqlServer/​EntityFrameworkCore/​BulkOperations/​SqlServerMergeAction.cs Defines insert/update actions.
src/​Thinktecture.EntityFrameworkCore.SqlServer/​EntityFrameworkCore/​BulkOperations/​SqlServerBulkOperationExecutor.MergeOutput.cs Implements projected merge execution.
src/​Thinktecture.EntityFrameworkCore.SqlServer/​EntityFrameworkCore/​BulkOperations/​SqlServerBulkOperationExecutor.cs Integrates optional merge output.
src/​Thinktecture.EntityFrameworkCore.Sqlite.Core/​EntityFrameworkCore/​Infrastructure/​SqliteDbContextOptionsExtension.cs Registers the output executor.
src/​Thinktecture.EntityFrameworkCore.Sqlite.Core/​EntityFrameworkCore/​BulkOperations/​SqliteReturning.cs Collects projected SQLite results.
src/​Thinktecture.EntityFrameworkCore.Sqlite.Core/​EntityFrameworkCore/​BulkOperations/​SqliteCommandBuilder.cs Appends RETURNING clauses.
src/​Thinktecture.EntityFrameworkCore.Sqlite.Core/​EntityFrameworkCore/​BulkOperations/​SqliteBulkOperationExecutor.Returning.cs Implements SQLite output overloads.
src/​Thinktecture.EntityFrameworkCore.Sqlite.Core/​EntityFrameworkCore/​BulkOperations/​SqliteBulkOperationExecutor.cs Reads root-entity results during writes.
src/​Thinktecture.EntityFrameworkCore.PostgreSQL/​EntityFrameworkCore/​Infrastructure/​NpgsqlDbContextOptionsExtension.cs Registers the output executor.
src/​Thinktecture.EntityFrameworkCore.PostgreSQL/​EntityFrameworkCore/​BulkOperations/​NpgsqlBulkOperationExecutor.Returning.cs Implements PostgreSQL output overloads.
src/​Thinktecture.EntityFrameworkCore.PostgreSQL/​EntityFrameworkCore/​BulkOperations/​NpgsqlBulkOperationExecutor.cs Adds optional RETURNING clauses.
src/​Thinktecture.EntityFrameworkCore.BulkOperations/​Extensions/​Internal/​BulkOperationsSqlExecutor.cs Adds EF Core reader execution.
src/​Thinktecture.EntityFrameworkCore.BulkOperations/​Extensions/​BulkOperationsDbContextExtensions.cs Exposes provider-independent output overloads.
src/​Thinktecture.EntityFrameworkCore.BulkOperations/​EntityFrameworkCore/​BulkOperations/​Internal/​BulkOperationReturningProjection.cs Selects columns and materializes results.
src/​Thinktecture.EntityFrameworkCore.BulkOperations/​EntityFrameworkCore/​BulkOperations/​IBulkOperationOutputExecutor.cs Defines the output executor contract.
src/​Thinktecture.EntityFrameworkCore.BulkOperations/​EntityFrameworkCore/​BulkOperations/​BulkOperationOutput.cs Defines the shared output row.

Review effort: Balanced

…roperties on NULL

The rows that BulkInsertOrUpdate and BulkUpdate return were created with the type of the input and skipped columns that are NULL. Review of the pull request found three problems that this commit fixes.

A NULL column left the value that the constructor or an initializer assigned, so a nullable property initialized to a non-null value was returned as that value, and so was every deleted column of an inserted row on SQL Server. A NULL now resets the property: a reference type and a nullable value type to null, any other value type to its default value.

A TPH hierarchy with an abstract base type failed after the write, because the abstract type cannot be created, and a hierarchy with a concrete base type returned base instances without the properties of the derived types. The mapper now reads the discriminator column and creates the type that the stored row has, which can differ from the type of the input. A whole-entity projection reads the properties of the derived types as well, and each entity receives only the properties of its own type.

A projection that read the whole entity ignored the members it read besides, so row => new { Entity = row.Inserted, row.Inserted.Parent } executed the write and returned an unloaded navigation instead of throwing NotSupportedException. The members are validated in every case.

The SQL Server plan and the RETURNING projection of PostgreSQL and SQLite share the mapping in BulkOperationOutputMapper, so all providers get the same behaviour.
Copilot AI balanced review requested due to automatic review settings December 3, 2026 12:27

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The output mapper silently omits mapped complex properties in whole-entity projections and fails to build output plans for scalar properties using provider-specific reader methods.

No open issues 🎉

2 previously missed issues

In code that hasn't changed since last review

Medium severity Whole-entity projections omit mapped complex properties

src/​Thinktecture.EntityFrameworkCore.BulkOperations/​EntityFrameworkCore/​BulkOperations/​Internal/​BulkOperationOutputMapper.cs:164

Whole-entity output silently omits mapped complex properties because GetProperties() does not include their flattened scalar members. For example, the existing TestEntityWithComplexType can be bulk-upserted, but selecting row.Inserted returns an instance whose Boundary was never initialized; accessing Boundary then throws instead of exposing the stored values. Please either materialize the complex properties or reject whole-entity projections containing unsupported mapped complex properties with NotSupportedException before writing.

Medium severity Provider-specific reader methods break scalar output plans

src/​Thinktecture.EntityFrameworkCore.BulkOperations/​EntityFrameworkCore/​BulkOperations/​Internal/​BulkOperationOutputMapper.cs:261

Provider mappings can return reader methods declared on a provider-specific reader, such as SQL Server's GetDateTimeOffset/GetTimeSpan. Passing an expression typed as DbDataReader to those methods makes Expression.Call throw ArgumentException while creating the output plan, so selecting these mapped scalar properties fails before execution. Cast the reader expression to the method's declaring type first.

6 resolved since last review

Review effort: Balanced

…d provider specific reader methods

A projection of the whole entity returned an entity without the values of its complex properties and of owned types that are stored in the same table, because the mapper reads the scalar properties of the entity type only. Accessing such a member returned an uninitialized value or threw. BulkOperationOutputMapper now throws NotSupportedException before the statement runs and names the member, so the caller selects the scalar properties explicitly.

The data reader method of a type mapping can be declared on the reader of the provider instead of DbDataReader. The mapper calls it through a cast to the declaring type, because Expression.Call rejects the DbDataReader instance for such a method. Neither the SQL Server nor the PostgreSQL provider returns such a method for the scalar types that the new tests cover, so the tests guard the creation of the mapper for these types.
Copilot AI balanced review requested due to automatic review settings December 3, 2026 12:44

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The output mapper checks only declared members, missing inherited owned navigations and allowing persisted entities to be returned with missing data instead of rejecting the mapping before writing.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Medium severity Validate inherited owned navigations and complex properties

src/​Thinktecture.EntityFrameworkCore.BulkOperations/​EntityFrameworkCore/​BulkOperations/​Internal/​BulkOperationOutputMapper.cs:171

Inherited owned navigations are missed because only declared members are checked. For example, returning the whole entity for a Car collection on SQLite succeeds but leaves Vehicle.Inline null, even though its columns were persisted. Inspect inherited navigations and complex properties too, so this mapping is rejected before writing rather than returning an incomplete entity.

Review effort: Balanced

…rojections

The check for members that a whole-entity projection cannot return looked at the members that are declared on the entity type and on its derived types. The members that the entity type inherits from its base types were missed, so returning the whole entity of a derived type such as Car succeeded and left the owned type that Vehicle declares (Inline) uninitialized, although its columns were written. The inherited complex properties and owned navigations are checked as well now, so the mapping is rejected with NotSupportedException before the statement runs.
Copilot AI balanced review requested due to automatic review settings December 3, 2026 13:23

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@pengweiqhca
pengweiqhca changed the base branch from master to releases/10.0.x December 5, 2026 00:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants