From 4f0aa860e4a078712044d418f5ffc283d0fa34be Mon Sep 17 00:00:00 2001 From: pengweiqhca Date: Thu, 3 Dec 2026 17:36:19 +0800 Subject: [PATCH 1/7] Add BulkOperationsSqlExecutor.ExecuteReaderAsync to read the result of 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. --- .../Internal/BulkOperationsSqlExecutor.cs | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/src/Thinktecture.EntityFrameworkCore.BulkOperations/Extensions/Internal/BulkOperationsSqlExecutor.cs b/src/Thinktecture.EntityFrameworkCore.BulkOperations/Extensions/Internal/BulkOperationsSqlExecutor.cs index 16b55a99..1e78cb22 100644 --- a/src/Thinktecture.EntityFrameworkCore.BulkOperations/Extensions/Internal/BulkOperationsSqlExecutor.cs +++ b/src/Thinktecture.EntityFrameworkCore.BulkOperations/Extensions/Internal/BulkOperationsSqlExecutor.cs @@ -1,5 +1,6 @@ using System.Collections.ObjectModel; using System.ComponentModel; +using System.Data.Common; using System.Diagnostics.CodeAnalysis; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -32,6 +33,50 @@ public static Task ExecuteNonQueryAsync(DatabaseFacade database, string sql return ExecuteNonQueryAsync(database, database.GetService().Build(sql), ReadOnlyDictionary.Empty, cancellationToken); } + /// + /// Executes a statement without parameters and reads its result with . + /// The text is sent unchanged, see . + /// The statement runs through the command pipeline of EF Core, so logging, interceptors, the current transaction and the command timeout of the context apply. + /// + /// The database facade of the context. + /// The statement. + /// Reads the result; the reader is disposed afterwards. + /// Cancellation token. + /// Type of the result. + /// The result of . + /// , or is null. + [SuppressMessage("Usage", "EF1001", MessageId = "Internal EF Core API usage.")] + public static async Task ExecuteReaderAsync( + DatabaseFacade database, + string sql, + Func> readAsync, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(database); + ArgumentNullException.ThrowIfNull(sql); + ArgumentNullException.ThrowIfNull(readAsync); + + var accessor = (IDatabaseFacadeDependenciesAccessor)database; + var dependencies = (IRelationalDatabaseFacadeDependencies)accessor.Dependencies; + var criticalSection = dependencies.CoreOptions.AreThreadSafetyChecksEnabled ? dependencies.ConcurrencyDetector.EnterCriticalSection() : (ConcurrencyDetectorCriticalSectionDisposer?)null; + + try + { + var command = database.GetService().Build(sql); + var parameterObject = new RelationalCommandParameterObject(dependencies.RelationalConnection, ReadOnlyDictionary.Empty, null, accessor.Context, dependencies.CommandLogger, CommandSource.ExecuteSqlRaw); + var reader = await command.ExecuteReaderAsync(parameterObject, cancellationToken).ConfigureAwait(false); + + await using (reader.ConfigureAwait(false)) + { + return await readAsync(reader.DbDataReader, cancellationToken).ConfigureAwait(false); + } + } + finally + { + criticalSection?.Dispose(); + } + } + /// /// Executes a command. Same as ExecuteSqlRawAsync, but with a command and the parameter values of EF Core. /// From fc441fdd53e605094f3657fbf861cf2f3ae61522 Mon Sep 17 00:00:00 2001 From: pengweiqhca Date: Thu, 3 Dec 2026 17:36:20 +0800 Subject: [PATCH 2/7] Return the OUTPUT rows of the SQL Server MERGE statements of BulkInsertOrUpdate and BulkUpdate DbContext.BulkInsertOrUpdateAsync and DbContext.BulkUpdateAsync have new overloads for SQL Server that take a projection of SqlServerMergeOutput 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. --- ...ServerBulkOperationExecutor.MergeOutput.cs | 73 +++++ .../SqlServerBulkOperationExecutor.cs | 43 ++- .../BulkOperations/SqlServerMergeAction.cs | 17 + .../BulkOperations/SqlServerMergeOutput.cs | 34 ++ .../SqlServerMergeOutputPlan.cs | 306 ++++++++++++++++++ ...SqlServerMergeOutputDbContextExtensions.cs | 73 +++++ .../MergeOutput.cs | 141 ++++++++ 7 files changed, 678 insertions(+), 9 deletions(-) create mode 100644 src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.MergeOutput.cs create mode 100644 src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeAction.cs create mode 100644 src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeOutput.cs create mode 100644 src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeOutputPlan.cs create mode 100644 src/Thinktecture.EntityFrameworkCore.SqlServer/Extensions/SqlServerMergeOutputDbContextExtensions.cs create mode 100644 tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutorTests/MergeOutput.cs diff --git a/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.MergeOutput.cs b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.MergeOutput.cs new file mode 100644 index 00000000..b6a9a0ae --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.MergeOutput.cs @@ -0,0 +1,73 @@ +using System.Linq.Expressions; +using Thinktecture.EntityFrameworkCore.BulkOperations.Internal; +using Thinktecture.Internal; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +public sealed partial class SqlServerBulkOperationExecutor +{ + /// + /// Updates existing rows and inserts the missing ones (MERGE) and returns the OUTPUT rows selected by . + /// + /// Entities to insert or update. + /// Options. + /// Selects the result, for example row => new { row.Inserted.Id, row.Action }. Only the properties that the expression reads are returned by the database. + /// Cancellation token. + /// Type of the entity. + /// Type of the result. + /// One result per inserted or updated row. The order is not defined, it is not the order of . + /// , or is null. + /// reads a member that is not a scalar property mapped to a column. + public async Task> BulkInsertOrUpdateAsync( + IEnumerable entities, + SqlServerBulkInsertOrUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class + { + ArgumentNullException.ThrowIfNull(entities); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(output); + + var plan = SqlServerMergeOutputPlan.Create(_ctx.Model.GetEntityTypeOrTempTableEntityType(), _sqlGenerationHelper, output); + + return await BulkInsertOrUpdateAsync(entities, options, plan.Sql, (statement, token) => ExecuteMergeAsync(plan, statement, token), cancellationToken); + } + + /// + /// Updates existing rows (MERGE) and returns the OUTPUT rows selected by . + /// + /// Entities to update. + /// Options. + /// Selects the result, for example row => new { row.Inserted.Id, OldName = row.Deleted.Name }. Only the properties that the expression reads are returned by the database. + /// Cancellation token. + /// Type of the entity. + /// Type of the result. + /// One result per updated row. The order is not defined, it is not the order of . + /// , or is null. + /// reads a member that is not a scalar property mapped to a column. + public async Task> BulkUpdateAsync( + IEnumerable entities, + SqlServerBulkUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class + { + ArgumentNullException.ThrowIfNull(entities); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(output); + + var plan = SqlServerMergeOutputPlan.Create(_ctx.Model.GetEntityTypeOrTempTableEntityType(), _sqlGenerationHelper, output); + + return await BulkUpdateAsync(entities, options, plan.Sql, (statement, token) => ExecuteMergeAsync(plan, statement, token), cancellationToken); + } + + private Task> ExecuteMergeAsync( + SqlServerMergeOutputPlan plan, + string mergeStatement, + CancellationToken cancellationToken) + where T : class + { + return BulkOperationsSqlExecutor.ExecuteReaderAsync(_ctx.Database, mergeStatement, plan.ReadAsync, cancellationToken); + } +} diff --git a/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.cs b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.cs index 00d23c56..3544aca2 100644 --- a/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.cs +++ b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.cs @@ -473,10 +473,20 @@ public async Task BulkUpdateAsync( if (options is not SqlServerBulkUpdateOptions sqlServerOptions) sqlServerOptions = new SqlServerBulkUpdateOptions(options); - return await BulkUpdateAsync(entities, sqlServerOptions, cancellationToken); + return await BulkUpdateAsync(entities, sqlServerOptions, null, ExecuteMergeAsync, cancellationToken); } - private async Task BulkUpdateAsync(IEnumerable entities, SqlServerBulkUpdateOptions options, CancellationToken cancellationToken) + private Task ExecuteMergeAsync(string mergeStatement, CancellationToken cancellationToken) + { + return BulkOperationsSqlExecutor.ExecuteNonQueryAsync(_ctx.Database, mergeStatement, cancellationToken); + } + + private async Task BulkUpdateAsync( + IEnumerable entities, + SqlServerBulkUpdateOptions options, + SqlServerMergeOutputSql? output, + Func> executeMergeAsync, + CancellationToken cancellationToken) where T : class { var entityType = _ctx.Model.GetEntityTypeOrTempTableEntityType(); @@ -490,9 +500,9 @@ private async Task BulkUpdateAsync(IEnumerable entities, SqlServerBul var tempTableOptions = options.GetTempTableBulkInsertOptions(); await using var tempTable = await BulkInsertIntoTempTableAsync(entities, tempTableOptions, cancellationToken); - var mergeStatement = CreateMergeCommand(entityType, tableName.Schema, tableName.Name, tempTable.Name, options, null, propertiesForUpdate, options.KeyProperties.DetermineKeyProperties(entityType)); + var mergeStatement = CreateMergeCommand(entityType, tableName.Schema, tableName.Name, tempTable.Name, options, null, propertiesForUpdate, options.KeyProperties.DetermineKeyProperties(entityType), output); - return await BulkOperationsSqlExecutor.ExecuteNonQueryAsync(_ctx.Database, mergeStatement, cancellationToken); + return await executeMergeAsync(mergeStatement, cancellationToken); } /// @@ -508,10 +518,15 @@ public async Task BulkInsertOrUpdateAsync( if (options is not SqlServerBulkInsertOrUpdateOptions sqlServerOptions) sqlServerOptions = new SqlServerBulkInsertOrUpdateOptions(options); - return await BulkInsertOrUpdateAsync(entities, sqlServerOptions, cancellationToken); + return await BulkInsertOrUpdateAsync(entities, sqlServerOptions, null, ExecuteMergeAsync, cancellationToken); } - private async Task BulkInsertOrUpdateAsync(IEnumerable entities, SqlServerBulkInsertOrUpdateOptions options, CancellationToken cancellationToken) + private async Task BulkInsertOrUpdateAsync( + IEnumerable entities, + SqlServerBulkInsertOrUpdateOptions options, + SqlServerMergeOutputSql? output, + Func> executeMergeAsync, + CancellationToken cancellationToken) where T : class { var entityType = _ctx.Model.GetEntityTypeOrTempTableEntityType(); @@ -526,9 +541,9 @@ private async Task BulkInsertOrUpdateAsync(IEnumerable entities, SqlS var tempTableOptions = options.GetTempTableBulkInsertOptions(); await using var tempTable = await BulkInsertIntoTempTableAsync(entities, tempTableOptions, cancellationToken); - var mergeStatement = CreateMergeCommand(entityType, tableName.Schema, tableName.Name, tempTable.Name, options, propertiesForInsert, propertiesForUpdate, options.KeyProperties.DetermineKeyProperties(entityType)); + var mergeStatement = CreateMergeCommand(entityType, tableName.Schema, tableName.Name, tempTable.Name, options, propertiesForInsert, propertiesForUpdate, options.KeyProperties.DetermineKeyProperties(entityType), output); - return await BulkOperationsSqlExecutor.ExecuteNonQueryAsync(_ctx.Database, mergeStatement, cancellationToken); + return await executeMergeAsync(mergeStatement, cancellationToken); } private string CreateMergeCommand( @@ -539,7 +554,8 @@ private string CreateMergeCommand( T options, IReadOnlyList? propertiesToInsert, IReadOnlyList propertiesToUpdate, - IReadOnlyList keyProperties) + IReadOnlyList keyProperties, + SqlServerMergeOutputSql? output) where T : ISqlServerMergeOperationOptions { var sb = _stringBuilderPool.Get(); @@ -549,6 +565,9 @@ private string CreateMergeCommand( var storeObject = StoreObjectIdentifier.Create(entityType, StoreObjectType.Table) ?? throw new Exception($"Could not create StoreObjectIdentifier for table '{entityType.Name}'."); + if (output is not null) + sb.AppendLine(output.Declaration); + sb.Append("MERGE INTO ") .Append(_sqlGenerationHelper.DelimitIdentifier(tableName, schema)); @@ -655,8 +674,14 @@ private string CreateMergeCommand( sb.Append(")"); } + if (output is not null) + sb.AppendLine().Append(output.OutputClause); + sb.Append(_sqlGenerationHelper.StatementTerminator); + if (output is not null) + sb.AppendLine().Append(output.Select); + return sb.ToString(); } finally diff --git a/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeAction.cs b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeAction.cs new file mode 100644 index 00000000..aa7a510d --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeAction.cs @@ -0,0 +1,17 @@ +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +/// +/// The action a SQL Server MERGE statement executed for a row ($action). +/// +public enum SqlServerMergeAction +{ + /// + /// The row was inserted. + /// + Insert, + + /// + /// The row was updated. + /// + Update +} diff --git a/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeOutput.cs b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeOutput.cs new file mode 100644 index 00000000..703c6be3 --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeOutput.cs @@ -0,0 +1,34 @@ +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +/// +/// One row of the OUTPUT clause of a SQL Server MERGE statement. +/// Use it in the projection of BulkInsertOrUpdateAsync and BulkUpdateAsync to select the columns to return: +/// output => new { output.Inserted.Id, OldName = output.Deleted.Name, output.Action }. +/// +/// Type of the entity. +public sealed class SqlServerMergeOutput + where T : class +{ + /// + /// The action the MERGE statement executed for the row. + /// + public SqlServerMergeAction Action { get; internal set; } + + /// + /// The row after the operation (inserted.*). + /// + /// + /// Only the properties that the projection reads are loaded; the other properties keep their default values. + /// + public T Inserted { get; internal set; } = null!; + + /// + /// The row before the operation (deleted.*). + /// For a row that was inserted the database returns NULL for all columns, so nullable properties are null + /// and the other properties keep their default values. Use to tell the cases apart. + /// + /// + /// Only the properties that the projection reads are loaded; the other properties keep their default values. + /// + public T Deleted { get; internal set; } = null!; +} diff --git a/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeOutputPlan.cs b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeOutputPlan.cs new file mode 100644 index 00000000..9a88ab82 --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeOutputPlan.cs @@ -0,0 +1,306 @@ +using System.Data.Common; +using System.Diagnostics.CodeAnalysis; +using System.Linq.Expressions; +using System.Text; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +/// +/// The parts of the SQL batch that return the OUTPUT rows of a MERGE statement. +/// +/// Declares the table variable that receives the rows; precedes the MERGE statement. +/// The OUTPUT ... INTO clause; ends the MERGE statement. +/// Selects the rows of the table variable; follows the MERGE statement. +internal sealed record SqlServerMergeOutputSql(string Declaration, string OutputClause, string Select); + +/// +/// Translates the projection of a MERGE result to an OUTPUT clause and materializes the returned rows. +/// +/// +/// The rows are written into a table variable first (OUTPUT ... INTO), because SQL Server rejects OUTPUT without INTO if the target table has enabled triggers. +/// +[SuppressMessage("Usage", "EF1001:Internal EF Core API usage.")] +internal sealed class SqlServerMergeOutputPlan + where T : class +{ + private const string _TABLE_VARIABLE = "@MergeOutput"; + private const string _ACTION_COLUMN = "Action"; + + private readonly OutputColumn[] _columns; + private readonly Func, TResult> _projection; + private readonly Func _createEntity; + private readonly bool _usesInserted; + private readonly bool _usesDeleted; + + public SqlServerMergeOutputSql Sql { get; } + + private SqlServerMergeOutputPlan( + OutputColumn[] columns, + Func, TResult> projection, + Func createEntity, + SqlServerMergeOutputSql sql) + { + _columns = columns; + _projection = projection; + _createEntity = createEntity; + _usesInserted = columns.Any(static column => column.IsInserted); + _usesDeleted = columns.Any(static column => !column.IsInserted); + Sql = sql; + } + + public static SqlServerMergeOutputPlan Create( + IEntityType entityType, + ISqlGenerationHelper sqlGenerationHelper, + Expression, TResult>> output) + { + var storeObject = StoreObjectIdentifier.Create(entityType, StoreObjectType.Table) + ?? throw new InvalidOperationException($"Could not create StoreObjectIdentifier for table '{entityType.Name}'."); + + var collector = new MemberCollector(output.Parameters[0]); + collector.Visit(output.Body); + + var columns = new List(); + AddColumns(columns, entityType, storeObject, isInserted: true, collector.AllInserted, collector.InsertedMembers); + AddColumns(columns, entityType, storeObject, isInserted: false, collector.AllDeleted, collector.DeletedMembers); + + return new SqlServerMergeOutputPlan( + columns.ToArray(), + output.Compile(), + CreateEntityFactory(), + CreateSql(sqlGenerationHelper, columns)); + } + + public async Task> ReadAsync(DbDataReader reader, CancellationToken cancellationToken) + { + var results = new List(); + + while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) + { + var row = new SqlServerMergeOutput { Action = ParseAction(reader.GetString(0)) }; + + if (_usesInserted) + row.Inserted = _createEntity(); + + if (_usesDeleted) + row.Deleted = _createEntity(); + + foreach (var column in _columns) + { + // A NULL keeps the default of the property: the deleted columns of an inserted row are NULL. + if (reader.IsDBNull(column.Ordinal)) + continue; + + var value = column.Read(reader, column.Ordinal); + + if (column.Converter is not null) + value = column.Converter.ConvertFromProvider(value); + + column.Setter(column.IsInserted ? row.Inserted : row.Deleted, value); + } + + results.Add(_projection(row)); + } + + return results; + } + + private static SqlServerMergeAction ParseAction(string action) + { + return action switch + { + "INSERT" => SqlServerMergeAction.Insert, + "UPDATE" => SqlServerMergeAction.Update, + _ => throw new InvalidOperationException($"The MERGE statement returned the unexpected action '{action}'.") + }; + } + + private static void AddColumns( + List columns, + IEntityType entityType, + StoreObjectIdentifier storeObject, + bool isInserted, + bool all, + HashSet memberNames) + { + IEnumerable properties; + + if (all) + { + properties = entityType.GetProperties().Where(property => !property.IsShadowProperty() && property.GetColumnName(storeObject) is not null); + } + else + { + properties = memberNames.Select(name => entityType.FindProperty(name) is { } property && property.GetColumnName(storeObject) is not null + ? property + : throw new NotSupportedException($"'{name}' is not a scalar property of the entity '{entityType.DisplayName()}' that is mapped to a column of table '{storeObject.Name}'. Only such properties can be selected from the OUTPUT clause.")); + } + + foreach (var property in properties) + { + // The first column of the result is the action. + columns.Add(new OutputColumn(isInserted, property, storeObject, columns.Count + 1)); + } + } + + private static Func CreateEntityFactory() + { + var constructor = typeof(T).GetConstructor(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic, Type.EmptyTypes); + + // The properties that are not selected keep their default values, so the constructor is not required. + return constructor is null || typeof(T).IsAbstract + ? static () => (T)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(T)) + : Expression.Lambda>(Expression.New(constructor)).Compile(); + } + + private static SqlServerMergeOutputSql CreateSql(ISqlGenerationHelper sqlGenerationHelper, List columns) + { + var action = sqlGenerationHelper.DelimitIdentifier(_ACTION_COLUMN); + + var declaration = new StringBuilder("DECLARE ").Append(_TABLE_VARIABLE).Append(" TABLE (").Append(action).Append(" nvarchar(10) NOT NULL"); + var output = new StringBuilder("OUTPUT $action"); + var into = new StringBuilder(action); + var select = new StringBuilder("SELECT ").Append(action); + + foreach (var column in columns) + { + var name = sqlGenerationHelper.DelimitIdentifier(column.Name); + + declaration.Append(", ").Append(name).Append(' ').Append(column.StoreType).Append(" NULL"); + output.Append(", ").Append(column.IsInserted ? "inserted." : "deleted.").Append(sqlGenerationHelper.DelimitIdentifier(column.ColumnName)); + into.Append(", ").Append(name); + select.Append(", ").Append(name); + } + + return new SqlServerMergeOutputSql( + declaration.Append(");").ToString(), + output.Append(" INTO ").Append(_TABLE_VARIABLE).Append(" (").Append(into).Append(')').ToString(), + select.Append(" FROM ").Append(_TABLE_VARIABLE).Append(';').ToString()); + } + + private sealed class OutputColumn + { + public bool IsInserted { get; } + public int Ordinal { get; } + public string Name { get; } + public string ColumnName { get; } + public string StoreType { get; } + public ValueConverter? Converter { get; } + public Func Read { get; } + public Action Setter { get; } + + public OutputColumn(bool isInserted, IProperty property, StoreObjectIdentifier storeObject, int ordinal) + { + var typeMapping = property.GetRelationalTypeMapping(); + + IsInserted = isInserted; + Ordinal = ordinal; + Name = $"{(isInserted ? 'i' : 'd')}{ordinal}"; + ColumnName = property.GetColumnName(storeObject)!; + StoreType = GetStoreType(property.GetColumnType(storeObject) ?? typeMapping.StoreType); + Converter = typeMapping.Converter; + Read = CreateReader(typeMapping); + Setter = CreateSetter(property); + } + + // A rowversion/timestamp column cannot receive an explicit value. + private static string GetStoreType(string storeType) + { + return storeType.Equals("rowversion", StringComparison.OrdinalIgnoreCase) || storeType.Equals("timestamp", StringComparison.OrdinalIgnoreCase) + ? "binary(8)" + : storeType; + } + + // The setter or the backing field may be private, the setter may be init-only. + private static Action CreateSetter(IProperty property) + { + if (property.PropertyInfo?.SetMethod is { } setMethod) + { + var instance = Expression.Parameter(typeof(object)); + var value = Expression.Parameter(typeof(object)); + var call = Expression.Call(Expression.Convert(instance, setMethod.DeclaringType!), setMethod, Expression.Convert(value, setMethod.GetParameters()[0].ParameterType)); + + return Expression.Lambda>(call, instance, value).Compile(); + } + + var field = property.FieldInfo ?? throw new InvalidOperationException($"The property '{property.DeclaringType.DisplayName()}.{property.Name}' has neither a setter nor a backing field, so it cannot be selected from the OUTPUT clause."); + + return field.SetValue; + } + + private static Func CreateReader(RelationalTypeMapping typeMapping) + { + var reader = Expression.Parameter(typeof(DbDataReader)); + var ordinal = Expression.Parameter(typeof(int)); + var call = Expression.Call(reader, typeMapping.GetDataReaderMethod(), ordinal); + + return Expression.Lambda>(Expression.Convert(call, typeof(object)), reader, ordinal).Compile(); + } + } + + // Collects the members of "output.Inserted" and "output.Deleted" that the projection reads. + private sealed class MemberCollector(ParameterExpression parameter) : ExpressionVisitor + { + public HashSet InsertedMembers { get; } = []; + public HashSet DeletedMembers { get; } = []; + public bool AllInserted { get; private set; } + public bool AllDeleted { get; private set; } + + protected override Expression VisitMember(MemberExpression node) + { + // output.Inserted.Name + if (IsSide(node.Expression, out var isInserted)) + { + (isInserted ? InsertedMembers : DeletedMembers).Add(node.Member.Name); + return node; + } + + // output.Inserted: the whole entity + if (IsSide(node, out isInserted)) + { + if (isInserted) + AllInserted = true; + else + AllDeleted = true; + + return node; + } + + // output.Action + if (node.Expression == parameter) + return node; + + return base.VisitMember(node); + } + + protected override Expression VisitParameter(ParameterExpression node) + { + // The output row is used as a whole, for example passed to a method: load everything. + if (node == parameter) + { + AllInserted = true; + AllDeleted = true; + } + + return node; + } + + private bool IsSide(Expression? expression, out bool isInserted) + { + isInserted = false; + + if (expression is not MemberExpression { Expression: ParameterExpression owner } member || owner != parameter) + return false; + + if (member.Member.Name == nameof(SqlServerMergeOutput.Inserted)) + { + isInserted = true; + return true; + } + + return member.Member.Name == nameof(SqlServerMergeOutput.Deleted); + } + } +} diff --git a/src/Thinktecture.EntityFrameworkCore.SqlServer/Extensions/SqlServerMergeOutputDbContextExtensions.cs b/src/Thinktecture.EntityFrameworkCore.SqlServer/Extensions/SqlServerMergeOutputDbContextExtensions.cs new file mode 100644 index 00000000..3f04e1b5 --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.SqlServer/Extensions/SqlServerMergeOutputDbContextExtensions.cs @@ -0,0 +1,73 @@ +using System.Linq.Expressions; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Thinktecture.EntityFrameworkCore.BulkOperations; + +// ReSharper disable once CheckNamespace +namespace Thinktecture; + +/// +/// Extension methods for that return the OUTPUT rows (inserted.*, deleted.*) of a SQL Server MERGE statement. +/// +public static class SqlServerMergeOutputDbContextExtensions +{ + /// + /// Updates existing rows and inserts the missing ones (MERGE) and returns the OUTPUT rows selected by . + /// + /// Database context to use. + /// Entities to insert or update. + /// Options. + /// + /// Selects the result, for example row => new { row.Inserted.Id, OldName = row.Deleted.Name, row.Action }. + /// row.Inserted maps to inserted.*, row.Deleted to deleted.* and row.Action to $action. + /// Only the properties that the expression reads are requested from the database. + /// The deleted columns of an inserted row are NULL, so nullable properties are null and the others keep their default value. + /// + /// Cancellation token. + /// Type of the entity. + /// Type of the result. + /// One result per inserted or updated row. The order is not defined, it is not the order of . + /// , , or is null. + /// reads a member that is not a scalar property mapped to a column. + public static Task> BulkInsertOrUpdateAsync( + this DbContext ctx, + IEnumerable entities, + SqlServerBulkInsertOrUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class + { + ArgumentNullException.ThrowIfNull(ctx); + + return ctx.GetService().BulkInsertOrUpdateAsync(entities, options, output, cancellationToken); + } + + /// + /// Updates existing rows (MERGE) and returns the OUTPUT rows selected by . + /// + /// Database context to use. + /// Entities to update. + /// Options. + /// + /// Selects the result, for example row => new { row.Inserted.Id, OldName = row.Deleted.Name }. + /// row.Inserted maps to inserted.*, row.Deleted to deleted.* and row.Action to $action. + /// Only the properties that the expression reads are requested from the database. + /// + /// Cancellation token. + /// Type of the entity. + /// Type of the result. + /// One result per updated row. The order is not defined, it is not the order of . + /// , , or is null. + /// reads a member that is not a scalar property mapped to a column. + public static Task> BulkUpdateAsync( + this DbContext ctx, + IEnumerable entities, + SqlServerBulkUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class + { + ArgumentNullException.ThrowIfNull(ctx); + + return ctx.GetService().BulkUpdateAsync(entities, options, output, cancellationToken); + } +} diff --git a/tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutorTests/MergeOutput.cs b/tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutorTests/MergeOutput.cs new file mode 100644 index 00000000..3293a7cd --- /dev/null +++ b/tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutorTests/MergeOutput.cs @@ -0,0 +1,141 @@ +using Thinktecture.EntityFrameworkCore.TempTables; +using Thinktecture.TestDatabaseContext; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations.SqlServerBulkOperationExecutorTests; + +public class MergeOutput : IntegrationTestsBase +{ + private static readonly Guid _EXISTING_ID = new("79DA4171-C90B-4A5D-B0B5-D0A1E1BDF966"); + private static readonly Guid _NEW_ID = new("3DAEA618-B732-4BCA-A5A1-D1E075022DEC"); + + public MergeOutput(ITestOutputHelper testOutputHelper, SqlServerFixture sqlServerFixture) + : base(testOutputHelper, sqlServerFixture) + { + } + + [Fact] + public async Task Should_return_inserted_and_deleted_values_with_the_action_of_each_row() + { + var existingEntity = new TestEntity { Id = _EXISTING_ID, RequiredName = "Old", Count = 1 }; + ArrangeDbContext.Add(existingEntity); + await ArrangeDbContext.SaveChangesAsync(); + + existingEntity.RequiredName = "New"; + existingEntity.Count = 2; + var newEntity = new TestEntity { Id = _NEW_ID, RequiredName = "Inserted", Count = 3 }; + + var result = await ActDbContext.BulkInsertOrUpdateAsync( + new[] { existingEntity, newEntity }, + new SqlServerBulkInsertOrUpdateOptions(), + row => new { row.Inserted.Id, row.Inserted.Count, OldCount = row.Deleted.Count, OldNullableCount = row.Deleted.NullableCount, row.Action }); + + result.Should().BeEquivalentTo(new[] + { + new { Id = _EXISTING_ID, Count = 2, OldCount = 1, OldNullableCount = (int?)null, Action = SqlServerMergeAction.Update }, + // the deleted columns of an inserted row are NULL: a non-nullable property keeps its default value + new { Id = _NEW_ID, Count = 3, OldCount = 0, OldNullableCount = (int?)null, Action = SqlServerMergeAction.Insert } + }); + } + + [Fact] + public async Task Should_request_only_the_columns_that_the_projection_reads() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name", Count = 3 }; + + await ActDbContext.BulkInsertOrUpdateAsync(new[] { entity }, new SqlServerBulkInsertOrUpdateOptions(), row => row.Inserted.Id); + + var mergeStatement = ExecutedCommands.Should().ContainSingle(command => command.Contains("MERGE INTO", StringComparison.Ordinal)).Subject; + mergeStatement.Should().Contain("OUTPUT $action, inserted.[Id] INTO @MergeOutput ([Action], [i1]);") + .And.NotContain("deleted.") + .And.NotContain("inserted.[Count]"); + } + + [Fact] + public async Task Should_return_the_whole_entity_including_converted_properties_and_fields() + { + var entity = new TestEntity { Id = _NEW_ID, Name = "Name", RequiredName = "RequiredName", Count = 3, ConvertibleClass = new ConvertibleClass(42), PropertyWithBackingField = 7 }; + entity.SetPrivateField(5); + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { entity }, new SqlServerBulkInsertOrUpdateOptions(), row => row.Inserted); + + var inserted = result.Should().ContainSingle().Subject; + inserted.Should().BeEquivalentTo(entity, options => options.Excluding(e => e.Parent).Excluding(e => e.Children)); + inserted.GetPrivateField().Should().Be(5); + } + + [Fact] + public async Task Should_return_rows_of_a_table_with_an_enabled_trigger() + { + await ArrangeDbContext.Database.ExecuteSqlRawAsync($"CREATE TRIGGER [{Schema}].[TR_TestEntities_MergeOutput] ON [{Schema}].[TestEntities] AFTER INSERT, UPDATE AS BEGIN SET NOCOUNT ON; END"); + + try + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name", Count = 3 }; + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { entity }, new SqlServerBulkInsertOrUpdateOptions(), row => row.Inserted.Id); + + result.Should().Equal(_NEW_ID); + } + finally + { + await ArrangeDbContext.Database.ExecuteSqlRawAsync($"DROP TRIGGER [{Schema}].[TR_TestEntities_MergeOutput]"); + } + } + + [Fact] + public async Task Should_return_updated_rows_of_BulkUpdate() + { + var existingEntity = new TestEntity { Id = _EXISTING_ID, RequiredName = "Old", Count = 1 }; + ArrangeDbContext.Add(existingEntity); + await ArrangeDbContext.SaveChangesAsync(); + + existingEntity.Count = 2; + var missingEntity = new TestEntity { Id = _NEW_ID, RequiredName = "Missing", Count = 9 }; + + var result = await ActDbContext.BulkUpdateAsync( + new[] { existingEntity, missingEntity }, + new SqlServerBulkUpdateOptions(), + row => new { row.Inserted.Id, row.Inserted.Count, OldCount = row.Deleted.Count, row.Action }); + + result.Should().BeEquivalentTo(new[] { new { Id = _EXISTING_ID, Count = 2, OldCount = 1, Action = SqlServerMergeAction.Update } }); + } + + [Fact] + public async Task Should_return_an_empty_list_if_entities_is_empty() + { + var result = await ActDbContext.BulkInsertOrUpdateAsync(new List(), new SqlServerBulkInsertOrUpdateOptions(), row => row.Inserted.Id); + + result.Should().BeEmpty(); + } + + [Fact] + public async Task Should_use_the_table_name_of_the_table_name_provider() + { + await ArrangeDbContext.Database.ExecuteSqlRawAsync($"SELECT TOP 0 * INTO [{Schema}].[TestEntities_MergeOutput] FROM [{Schema}].[TestEntities]"); + + try + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name", Count = 3 }; + var options = new SqlServerBulkInsertOrUpdateOptions { TableNameProvider = IBulkOperationTableNameProvider.ForRootEntity("TestEntities_MergeOutput", Schema) }; + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { entity }, options, row => row.Inserted.Id); + + result.Should().Equal(_NEW_ID); + (await AssertDbContext.TestEntities.CountAsync()).Should().Be(0); + } + finally + { + await ArrangeDbContext.Database.ExecuteSqlRawAsync($"DROP TABLE [{Schema}].[TestEntities_MergeOutput]"); + } + } + + [Fact] + public async Task Should_throw_if_the_projection_reads_a_navigation() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name" }; + + await ActDbContext.Awaiting(ctx => ctx.BulkInsertOrUpdateAsync(new[] { entity }, new SqlServerBulkInsertOrUpdateOptions(), row => row.Inserted.Parent)) + .Should().ThrowAsync() + .WithMessage("'Parent' is not a scalar property*"); + } +} From 571627eca7a9e106b4ae3864a1249d4c279987e7 Mon Sep 17 00:00:00 2001 From: pengweiqhca Date: Thu, 3 Dec 2026 17:55:45 +0800 Subject: [PATCH 3/7] Return the inserted rows of BulkInsertOrUpdate and BulkUpdate on PostgreSQL and SQLite DbContext.BulkInsertOrUpdateAsync and DbContext.BulkUpdateAsync have new overloads that take a projection of BulkOperationOutput 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. --- .../BulkOperations/BulkOperationOutput.cs | 19 ++ .../IBulkOperationOutputExecutor.cs | 43 ++++ .../BulkOperationReturningProjection.cs | 212 ++++++++++++++++++ .../BulkOperationsDbContextExtensions.cs | 62 +++++ .../NpgsqlBulkOperationExecutor.Returning.cs | 57 +++++ .../NpgsqlBulkOperationExecutor.cs | 60 ++++- .../NpgsqlDbContextOptionsExtension.cs | 1 + .../SqliteBulkOperationExecutor.Returning.cs | 49 ++++ .../SqliteBulkOperationExecutor.cs | 56 ++++- .../BulkOperations/SqliteCommandBuilder.cs | 31 ++- .../BulkOperations/SqliteReturning.cs | 34 +++ .../SqliteDbContextOptionsExtension.cs | 1 + .../BulkOperationOutputAsync.cs | 98 ++++++++ .../BulkOperationOutputAsync.cs | 95 ++++++++ 14 files changed, 793 insertions(+), 25 deletions(-) create mode 100644 src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/BulkOperationOutput.cs create mode 100644 src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/IBulkOperationOutputExecutor.cs create mode 100644 src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationReturningProjection.cs create mode 100644 src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutor.Returning.cs create mode 100644 src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutor.Returning.cs create mode 100644 src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteReturning.cs create mode 100644 tests/Thinktecture.EntityFrameworkCore.PostgreSQL.Tests/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutorTests/BulkOperationOutputAsync.cs create mode 100644 tests/Thinktecture.EntityFrameworkCore.Sqlite.Tests/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutorTests/BulkOperationOutputAsync.cs diff --git a/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/BulkOperationOutput.cs b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/BulkOperationOutput.cs new file mode 100644 index 00000000..0b62f8aa --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/BulkOperationOutput.cs @@ -0,0 +1,19 @@ +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +/// +/// One row that a bulk operation returned from the database (RETURNING). +/// Use it in the projection of BulkInsertOrUpdateAsync and BulkUpdateAsync to select the columns to return: +/// output => new { output.Inserted.Id, output.Inserted.Name }. +/// +/// Type of the entity. +public sealed class BulkOperationOutput + where T : class +{ + /// + /// The row after the operation. + /// + /// + /// Only the properties that the projection reads are loaded; the other properties keep their default values. + /// + public T Inserted { get; internal set; } = null!; +} diff --git a/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/IBulkOperationOutputExecutor.cs b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/IBulkOperationOutputExecutor.cs new file mode 100644 index 00000000..c516b941 --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/IBulkOperationOutputExecutor.cs @@ -0,0 +1,43 @@ +using System.Linq.Expressions; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +/// +/// Executes bulk operations that return the affected rows (RETURNING). +/// +public interface IBulkOperationOutputExecutor +{ + /// + /// Updates that are in the table, the rest will be inserted, and returns the rows selected by . + /// + /// Entities to insert or update. + /// Options. + /// Selects the result, for example row => new { row.Inserted.Id }. + /// Cancellation token. + /// Entity type. + /// Type of the result. + /// One result per inserted or updated row. The order is not defined. + Task> BulkInsertOrUpdateAsync( + IEnumerable entities, + IBulkInsertOrUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class; + + /// + /// Updates that are in the table and returns the rows selected by . + /// + /// Entities to update. + /// Options. + /// Selects the result, for example row => new { row.Inserted.Id }. + /// Cancellation token. + /// Entity type. + /// Type of the result. + /// One result per updated row. The order is not defined. + Task> BulkUpdateAsync( + IEnumerable entities, + IBulkUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class; +} diff --git a/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationReturningProjection.cs b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationReturningProjection.cs new file mode 100644 index 00000000..bbb14720 --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationReturningProjection.cs @@ -0,0 +1,212 @@ +using System.Data.Common; +using System.Linq.Expressions; +using System.Runtime.CompilerServices; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations.Internal; + +/// +/// Translates the projection of a bulk operation result to the columns of a RETURNING clause and materializes the returned rows. +/// This is an internal API. It may be changed or removed without notice. +/// +/// Type of the entity. +/// Type of the result. +public sealed class BulkOperationReturningProjection + where T : class +{ + private readonly Column[] _columns; + private readonly Func, TResult> _projection; + private readonly Func _createEntity; + + /// + /// The names of the columns to return, in the order in which reads them. + /// + public IReadOnlyList ColumnNames { get; } + + private BulkOperationReturningProjection(Column[] columns, Func, TResult> projection, Func createEntity) + { + _columns = columns; + _projection = projection; + _createEntity = createEntity; + ColumnNames = columns.Select(static column => column.ColumnName).ToList(); + } + + /// + /// Creates the projection. + /// + /// The entity type of the table. + /// The projection of the result. + /// The projection. + /// reads a member that is not a scalar property mapped to a column. + public static BulkOperationReturningProjection Create(IEntityType entityType, Expression, TResult>> output) + { + ArgumentNullException.ThrowIfNull(entityType); + ArgumentNullException.ThrowIfNull(output); + + var storeObject = StoreObjectIdentifier.Create(entityType, StoreObjectType.Table) + ?? throw new InvalidOperationException($"Could not create StoreObjectIdentifier for table '{entityType.Name}'."); + + var collector = new MemberCollector(output.Parameters[0]); + collector.Visit(output.Body); + + var properties = collector.All + ? entityType.GetProperties().Where(property => !property.IsShadowProperty() && property.GetColumnName(storeObject) is not null).ToList() + : collector.Members.Select(name => entityType.FindProperty(name) is { } property && property.GetColumnName(storeObject) is not null + ? property + : throw new NotSupportedException($"'{name}' is not a scalar property of the entity '{entityType.DisplayName()}' that is mapped to a column of table '{storeObject.Name}'. Only such properties can be selected from the RETURNING clause.")) + .ToList(); + + // A statement without a column to return is invalid. The projection reads nothing from the row, so any column is good enough. + if (properties.Count == 0) + properties.Add(entityType.FindPrimaryKey()?.Properties[0] ?? entityType.GetProperties().First(property => property.GetColumnName(storeObject) is not null)); + + return new BulkOperationReturningProjection(properties.Select(property => new Column(property, storeObject)).ToArray(), output.Compile(), CreateEntityFactory()); + } + + /// + /// Reads the current row of . The columns are read by position, in the order of . + /// + /// The reader, positioned on a row. + /// The result of the projection. + public TResult Read(DbDataReader reader) + { + ArgumentNullException.ThrowIfNull(reader); + + var row = new BulkOperationOutput { Inserted = _createEntity() }; + + for (var i = 0; i < _columns.Length; i++) + { + // A NULL keeps the default of the property. + if (reader.IsDBNull(i)) + continue; + + var column = _columns[i]; + var value = column.Read(reader, i); + + if (column.Converter is not null) + value = column.Converter.ConvertFromProvider(value); + + column.Setter(row.Inserted, value); + } + + return _projection(row); + } + + /// + /// Reads all rows of . + /// + /// The reader. + /// Cancellation token. + /// The results of the projection. + public async Task> ReadAllAsync(DbDataReader reader, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(reader); + + var results = new List(); + + while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) + { + results.Add(Read(reader)); + } + + return results; + } + + private static Func CreateEntityFactory() + { + var constructor = typeof(T).GetConstructor(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic, Type.EmptyTypes); + + // The properties that are not selected keep their default values, so the constructor is not required. + return constructor is null || typeof(T).IsAbstract + ? static () => (T)RuntimeHelpers.GetUninitializedObject(typeof(T)) + : Expression.Lambda>(Expression.New(constructor)).Compile(); + } + + private sealed class Column + { + public string ColumnName { get; } + public ValueConverter? Converter { get; } + public Func Read { get; } + public Action Setter { get; } + + public Column(IProperty property, StoreObjectIdentifier storeObject) + { + var typeMapping = property.GetRelationalTypeMapping(); + + ColumnName = property.GetColumnName(storeObject)!; + Converter = typeMapping.Converter; + Read = CreateReader(typeMapping); + Setter = CreateSetter(property); + } + + // The setter or the backing field may be private, the setter may be init-only. + private static Action CreateSetter(IProperty property) + { + if (property.PropertyInfo?.SetMethod is { } setMethod) + { + var instance = Expression.Parameter(typeof(object)); + var value = Expression.Parameter(typeof(object)); + var call = Expression.Call(Expression.Convert(instance, setMethod.DeclaringType!), setMethod, Expression.Convert(value, setMethod.GetParameters()[0].ParameterType)); + + return Expression.Lambda>(call, instance, value).Compile(); + } + + var field = property.FieldInfo ?? throw new InvalidOperationException($"The property '{property.DeclaringType.DisplayName()}.{property.Name}' has neither a setter nor a backing field, so it cannot be selected from the RETURNING clause."); + + return field.SetValue; + } + + private static Func CreateReader(RelationalTypeMapping typeMapping) + { + var reader = Expression.Parameter(typeof(DbDataReader)); + var ordinal = Expression.Parameter(typeof(int)); + var call = Expression.Call(reader, typeMapping.GetDataReaderMethod(), ordinal); + + return Expression.Lambda>(Expression.Convert(call, typeof(object)), reader, ordinal).Compile(); + } + } + + // Collects the members of "output.Inserted" that the projection reads. + private sealed class MemberCollector(ParameterExpression parameter) : ExpressionVisitor + { + public HashSet Members { get; } = []; + public bool All { get; private set; } + + protected override Expression VisitMember(MemberExpression node) + { + // output.Inserted.Name + if (IsInserted(node.Expression)) + { + Members.Add(node.Member.Name); + return node; + } + + // output.Inserted: the whole entity + if (IsInserted(node)) + { + All = true; + return node; + } + + return base.VisitMember(node); + } + + protected override Expression VisitParameter(ParameterExpression node) + { + // The output row is used as a whole, for example passed to a method: load everything. + if (node == parameter) + All = true; + + return node; + } + + private bool IsInserted(Expression? expression) + { + return expression is MemberExpression { Expression: ParameterExpression owner } member + && owner == parameter + && member.Member.Name == nameof(BulkOperationOutput.Inserted); + } + } +} diff --git a/src/Thinktecture.EntityFrameworkCore.BulkOperations/Extensions/BulkOperationsDbContextExtensions.cs b/src/Thinktecture.EntityFrameworkCore.BulkOperations/Extensions/BulkOperationsDbContextExtensions.cs index cf7120ed..72c3c0da 100644 --- a/src/Thinktecture.EntityFrameworkCore.BulkOperations/Extensions/BulkOperationsDbContextExtensions.cs +++ b/src/Thinktecture.EntityFrameworkCore.BulkOperations/Extensions/BulkOperationsDbContextExtensions.cs @@ -1,5 +1,6 @@ using System.Linq.Expressions; using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; using Thinktecture.EntityFrameworkCore.BulkOperations; using Thinktecture.EntityFrameworkCore.Parameters; using Thinktecture.EntityFrameworkCore.TempTables; @@ -199,6 +200,67 @@ public static async Task BulkInsertOrUpdateAsync( .BulkInsertOrUpdateAsync(entities, options, cancellationToken).ConfigureAwait(false); } + /// + /// Updates that are in the table, the rest will be inserted, and returns the rows selected by (RETURNING). + /// + /// Database context. + /// Entities to insert or update. + /// Options. + /// + /// Selects the result, for example row => new { row.Inserted.Id, row.Inserted.Name }. row.Inserted is the row after the operation. + /// Only the properties that the expression reads are requested from the database. + /// + /// Cancellation token. + /// One result per inserted or updated row. The order is not defined, it is not the order of . + /// Entity type. + /// Type of the result. + /// , , or is null. + /// The database provider cannot return the rows of a bulk operation, or reads a member that is not a scalar property mapped to a column. + public static Task> BulkInsertOrUpdateAsync( + this DbContext ctx, + IEnumerable entities, + IBulkInsertOrUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class + { + return GetOutputExecutor(ctx).BulkInsertOrUpdateAsync(entities, options, output, cancellationToken); + } + + /// + /// Updates that are in the table and returns the rows selected by (RETURNING). + /// + /// Database context. + /// Entities to update. + /// Options. + /// + /// Selects the result, for example row => new { row.Inserted.Id, row.Inserted.Name }. row.Inserted is the row after the operation. + /// Only the properties that the expression reads are requested from the database. + /// + /// Cancellation token. + /// One result per updated row. The order is not defined, it is not the order of . + /// Entity type. + /// Type of the result. + /// , , or is null. + /// The database provider cannot return the rows of a bulk operation, or reads a member that is not a scalar property mapped to a column. + public static Task> BulkUpdateAsync( + this DbContext ctx, + IEnumerable entities, + IBulkUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class + { + return GetOutputExecutor(ctx).BulkUpdateAsync(entities, options, output, cancellationToken); + } + + private static IBulkOperationOutputExecutor GetOutputExecutor(DbContext ctx) + { + ArgumentNullException.ThrowIfNull(ctx); + + return ((IInfrastructure)ctx).Instance.GetService() + ?? throw new NotSupportedException("The database provider of the context cannot return the rows of a bulk operation."); + } /// /// Copies into a temp table and returns the query for accessing the inserted records. /// diff --git a/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutor.Returning.cs b/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutor.Returning.cs new file mode 100644 index 00000000..762ec985 --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutor.Returning.cs @@ -0,0 +1,57 @@ +using System.Linq.Expressions; +using Thinktecture.EntityFrameworkCore.BulkOperations.Internal; +using Thinktecture.Internal; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +public sealed partial class NpgsqlBulkOperationExecutor +{ + /// + public async Task> BulkInsertOrUpdateAsync( + IEnumerable entities, + IBulkInsertOrUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class + { + ArgumentNullException.ThrowIfNull(entities); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(output); + + if (options is not NpgsqlBulkInsertOrUpdateOptions npgsqlOptions) + npgsqlOptions = new NpgsqlBulkInsertOrUpdateOptions(options); + + var projection = BulkOperationReturningProjection.Create(_ctx.Model.GetEntityTypeOrTempTableEntityType(), output); + + return await BulkInsertOrUpdateAsync(entities, npgsqlOptions, projection.ColumnNames, (statement, token) => ExecuteReaderAsync(projection, statement, token), cancellationToken); + } + + /// + public async Task> BulkUpdateAsync( + IEnumerable entities, + IBulkUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class + { + ArgumentNullException.ThrowIfNull(entities); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(output); + + if (options is not NpgsqlBulkUpdateOptions npgsqlOptions) + npgsqlOptions = new NpgsqlBulkUpdateOptions(options); + + var projection = BulkOperationReturningProjection.Create(_ctx.Model.GetEntityTypeOrTempTableEntityType(), output); + + return await BulkUpdateAsync(entities, npgsqlOptions, projection.ColumnNames, (statement, token) => ExecuteReaderAsync(projection, statement, token), cancellationToken); + } + + private Task> ExecuteReaderAsync( + BulkOperationReturningProjection projection, + string statement, + CancellationToken cancellationToken) + where T : class + { + return BulkOperationsSqlExecutor.ExecuteReaderAsync(_ctx.Database, statement, projection.ReadAllAsync, cancellationToken); + } +} diff --git a/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutor.cs b/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutor.cs index 8e68497d..6144f792 100644 --- a/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutor.cs +++ b/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutor.cs @@ -23,7 +23,7 @@ namespace Thinktecture.EntityFrameworkCore.BulkOperations; [SuppressMessage("Usage", "EF1001:Internal EF Core API usage.")] public sealed partial class NpgsqlBulkOperationExecutor : IBulkInsertExecutor, ITempTableBulkInsertExecutor, IBulkUpdateExecutor, - IBulkInsertOrUpdateExecutor, INpgsqlTruncateTableExecutor + IBulkInsertOrUpdateExecutor, INpgsqlTruncateTableExecutor, IBulkOperationOutputExecutor { private readonly DbContext _ctx; private readonly IDiagnosticsLogger _logger; @@ -516,10 +516,20 @@ public async Task BulkUpdateAsync( if (options is not NpgsqlBulkUpdateOptions npgsqlOptions) npgsqlOptions = new NpgsqlBulkUpdateOptions(options); - return await BulkUpdateAsync(entities, npgsqlOptions, cancellationToken); + return await BulkUpdateAsync(entities, npgsqlOptions, null, ExecuteStatementAsync, cancellationToken); } - private async Task BulkUpdateAsync(IEnumerable entities, NpgsqlBulkUpdateOptions options, CancellationToken cancellationToken) + private Task ExecuteStatementAsync(string statement, CancellationToken cancellationToken) + { + return BulkOperationsSqlExecutor.ExecuteNonQueryAsync(_ctx.Database, statement, cancellationToken); + } + + private async Task BulkUpdateAsync( + IEnumerable entities, + NpgsqlBulkUpdateOptions options, + IReadOnlyList? returningColumns, + Func> executeAsync, + CancellationToken cancellationToken) where T : class { var entityType = _ctx.Model.GetEntityTypeOrTempTableEntityType(); @@ -533,9 +543,9 @@ private async Task BulkUpdateAsync(IEnumerable entities, NpgsqlBulkUp var tempTableOptions = options.GetTempTableBulkInsertOptions(); await using var tempTable = await BulkInsertIntoTempTableAsync(entities, tempTableOptions, cancellationToken); - var updateStatement = CreateUpdateCommand(entityType, tableName.Schema, tableName.Name, tempTable.Name, propertiesForUpdate, options.KeyProperties.DetermineKeyProperties(entityType)); + var updateStatement = CreateUpdateCommand(entityType, tableName.Schema, tableName.Name, tempTable.Name, propertiesForUpdate, options.KeyProperties.DetermineKeyProperties(entityType), returningColumns); - return await BulkOperationsSqlExecutor.ExecuteNonQueryAsync(_ctx.Database, updateStatement, cancellationToken); + return await executeAsync(updateStatement, cancellationToken); } /// @@ -551,10 +561,15 @@ public async Task BulkInsertOrUpdateAsync( if (options is not NpgsqlBulkInsertOrUpdateOptions npgsqlOptions) npgsqlOptions = new NpgsqlBulkInsertOrUpdateOptions(options); - return await BulkInsertOrUpdateAsync(entities, npgsqlOptions, cancellationToken); + return await BulkInsertOrUpdateAsync(entities, npgsqlOptions, null, ExecuteStatementAsync, cancellationToken); } - private async Task BulkInsertOrUpdateAsync(IEnumerable entities, NpgsqlBulkInsertOrUpdateOptions options, CancellationToken cancellationToken) + private async Task BulkInsertOrUpdateAsync( + IEnumerable entities, + NpgsqlBulkInsertOrUpdateOptions options, + IReadOnlyList? returningColumns, + Func> executeAsync, + CancellationToken cancellationToken) where T : class { var entityType = _ctx.Model.GetEntityTypeOrTempTableEntityType(); @@ -570,9 +585,9 @@ private async Task BulkInsertOrUpdateAsync(IEnumerable entities, Npgs await using var tempTable = await BulkInsertIntoTempTableAsync(entities, tempTableOptions, cancellationToken); var keyProperties = options.KeyProperties.DetermineKeyProperties(entityType); - var upsertStatement = CreateInsertOrUpdateCommand(entityType, tableName.Schema, tableName.Name, tempTable.Name, propertiesForInsert, propertiesForUpdate, keyProperties, options.ConflictDoNothing); + var upsertStatement = CreateInsertOrUpdateCommand(entityType, tableName.Schema, tableName.Name, tempTable.Name, propertiesForInsert, propertiesForUpdate, keyProperties, options.ConflictDoNothing, returningColumns); - return await BulkOperationsSqlExecutor.ExecuteNonQueryAsync(_ctx.Database, upsertStatement, cancellationToken); + return await executeAsync(upsertStatement, cancellationToken); } private string CreateUpdateCommand( @@ -581,7 +596,8 @@ private string CreateUpdateCommand( string tableName, string sourceTempTableName, IReadOnlyList propertiesToUpdate, - IReadOnlyList keyProperties) + IReadOnlyList keyProperties, + IReadOnlyList? returningColumns) { var sb = _stringBuilderPool.Get(); @@ -636,6 +652,9 @@ private string CreateUpdateCommand( isFirstIteration = false; } + // The source temp table has the same columns, so the columns of the target are qualified. + AppendReturning(sb, returningColumns, "d."); + sb.Append(_sqlGenerationHelper.StatementTerminator); return sb.ToString(); @@ -646,6 +665,22 @@ private string CreateUpdateCommand( } } + private void AppendReturning(StringBuilder sb, IReadOnlyList? returningColumns, string qualifier) + { + if (returningColumns is null) + return; + + sb.AppendLine().Append("RETURNING "); + + for (var i = 0; i < returningColumns.Count; i++) + { + if (i != 0) + sb.Append(", "); + + sb.Append(qualifier).Append(_sqlGenerationHelper.DelimitIdentifier(returningColumns[i])); + } + } + /// /// Performs a bulk update using a server-side query as the source. /// @@ -706,7 +741,8 @@ private string CreateInsertOrUpdateCommand( IReadOnlyList propertiesToInsert, IReadOnlyList propertiesToUpdate, IReadOnlyList keyProperties, - bool conflictDoNothing) + bool conflictDoNothing, + IReadOnlyList? returningColumns) { var sb = _stringBuilderPool.Get(); @@ -792,6 +828,8 @@ private string CreateInsertOrUpdateCommand( } } + AppendReturning(sb, returningColumns, string.Empty); + sb.Append(_sqlGenerationHelper.StatementTerminator); return sb.ToString(); diff --git a/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/Infrastructure/NpgsqlDbContextOptionsExtension.cs b/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/Infrastructure/NpgsqlDbContextOptionsExtension.cs index d61ce4a2..cabad468 100644 --- a/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/Infrastructure/NpgsqlDbContextOptionsExtension.cs +++ b/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/Infrastructure/NpgsqlDbContextOptionsExtension.cs @@ -149,6 +149,7 @@ public void ApplyServices(IServiceCollection services) services.TryAddScoped(provider => provider.GetRequiredService()); services.TryAddScoped(provider => provider.GetRequiredService()); services.TryAddScoped(provider => provider.GetRequiredService()); + services.TryAddScoped(provider => provider.GetRequiredService()); services.TryAddScoped(provider => provider.GetRequiredService()); services.TryAddScoped(provider => provider.GetRequiredService()); } diff --git a/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutor.Returning.cs b/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutor.Returning.cs new file mode 100644 index 00000000..9add8814 --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutor.Returning.cs @@ -0,0 +1,49 @@ +using System.Linq.Expressions; +using Thinktecture.EntityFrameworkCore.BulkOperations.Internal; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +public sealed partial class SqliteBulkOperationExecutor +{ + /// + public async Task> BulkInsertOrUpdateAsync( + IEnumerable entities, + IBulkInsertOrUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class + { + ArgumentNullException.ThrowIfNull(entities); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(output); + + if (options is not ISqliteBulkInsertOrUpdateOptions sqliteOptions) + sqliteOptions = new SqliteBulkInsertOrUpdateOptions(options); + + var returning = new SqliteReturning(BulkOperationReturningProjection.Create(_ctx.Model.GetEntityTypeOrTempTableEntityType(), output)); + await BulkInsertOrUpdateAsync(entities, sqliteOptions, returning, cancellationToken); + + return returning.Results; + } + + /// + public async Task> BulkUpdateAsync( + IEnumerable entities, + IBulkUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class + { + ArgumentNullException.ThrowIfNull(entities); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(output); + + if (options is not SqliteBulkUpdateOptions sqliteOptions) + sqliteOptions = new SqliteBulkUpdateOptions(options); + + var returning = new SqliteReturning(BulkOperationReturningProjection.Create(_ctx.Model.GetEntityTypeOrTempTableEntityType(), output)); + await BulkUpdateAsync(entities, sqliteOptions, returning, cancellationToken); + + return returning.Results; + } +} diff --git a/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutor.cs b/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutor.cs index b5ab6d47..6a2919e4 100644 --- a/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutor.cs +++ b/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutor.cs @@ -23,7 +23,7 @@ namespace Thinktecture.EntityFrameworkCore.BulkOperations; [SuppressMessage("Usage", "EF1001:Internal EF Core API usage.")] public sealed partial class SqliteBulkOperationExecutor : IBulkInsertExecutor, ITempTableBulkInsertExecutor, IBulkUpdateExecutor, - IBulkInsertOrUpdateExecutor, ITruncateTableExecutor + IBulkInsertOrUpdateExecutor, ITruncateTableExecutor, IBulkOperationOutputExecutor { private readonly DbContext _ctx; private readonly IDiagnosticsLogger _logger; @@ -130,7 +130,7 @@ private async Task BulkInsertAsync( var tableName = tableNameProvider.GetValidTableName(entityType); var ctx = bulkOperationContextFactory.CreateForBulkInsert(_ctx, entityType, options, properties); - return await ExecuteBulkOperationAsync(entitiesOrValues, tableName.Schema, tableName.Name, ctx, tableNameProvider, cancellationToken); + return await ExecuteBulkOperationAsync(entitiesOrValues, tableName.Schema, tableName.Name, ctx, tableNameProvider, null, cancellationToken); } /// @@ -146,19 +146,29 @@ public async Task BulkUpdateAsync( if (options is not SqliteBulkUpdateOptions sqliteOptions) sqliteOptions = new SqliteBulkUpdateOptions(options); + return await BulkUpdateAsync(entities, sqliteOptions, null, cancellationToken); + } + + private async Task BulkUpdateAsync( + IEnumerable entities, + SqliteBulkUpdateOptions sqliteOptions, + SqliteReturning? returning, + CancellationToken cancellationToken) + where T : class + { var entityType = _ctx.Model.GetEntityTypeOrTempTableEntityType(); - var propertiesToUpdate = options.PropertiesToUpdate.DeterminePropertiesForUpdate(entityType, null); + var propertiesToUpdate = sqliteOptions.PropertiesToUpdate.DeterminePropertiesForUpdate(entityType, null); var tableNameProvider = sqliteOptions.TableNameProvider; var tableName = tableNameProvider.GetValidTableName(entityType); var ctx = new BulkUpdateContext(_ctx, entityType, _ctx.GetService(), (SqliteConnection)_ctx.Database.GetDbConnection(), - options.KeyProperties.DetermineKeyProperties(entityType), + sqliteOptions.KeyProperties.DetermineKeyProperties(entityType), propertiesToUpdate, sqliteOptions.AutoIncrementBehavior); - return await ExecuteBulkOperationAsync(entities, tableName.Schema, tableName.Name, ctx, tableNameProvider, cancellationToken); + return await ExecuteBulkOperationAsync(entities, tableName.Schema, tableName.Name, ctx, tableNameProvider, returning, cancellationToken); } /// @@ -174,6 +184,16 @@ public async Task BulkInsertOrUpdateAsync( if (!(options is ISqliteBulkInsertOrUpdateOptions sqliteOptions)) sqliteOptions = new SqliteBulkInsertOrUpdateOptions(options); + return await BulkInsertOrUpdateAsync(entities, sqliteOptions, null, cancellationToken); + } + + private async Task BulkInsertOrUpdateAsync( + IEnumerable entities, + ISqliteBulkInsertOrUpdateOptions sqliteOptions, + SqliteReturning? returning, + CancellationToken cancellationToken) + where T : class + { var entityType = _ctx.Model.GetEntityTypeOrTempTableEntityType(); var propertiesToInsert = sqliteOptions.PropertiesToInsert.DeterminePropertiesForInsert(entityType, null); var propertiesToUpdate = sqliteOptions.PropertiesToUpdate.DeterminePropertiesForUpdate(entityType, true); @@ -188,7 +208,7 @@ public async Task BulkInsertOrUpdateAsync( propertiesToUpdate, sqliteOptions.AutoIncrementBehavior); - return await ExecuteBulkOperationAsync(entities, tableName.Schema, tableName.Name, ctx, tableNameProvider, cancellationToken); + return await ExecuteBulkOperationAsync(entities, tableName.Schema, tableName.Name, ctx, tableNameProvider, returning, cancellationToken); } private async Task ExecuteBulkOperationAsync( @@ -197,6 +217,7 @@ private async Task ExecuteBulkOperationAsync( string tableName, ISqliteBulkOperationContext bulkOperationContext, IBulkOperationTableNameProvider tableNameProvider, + SqliteReturning? returning, CancellationToken cancellationToken) { await _ctx.Database.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); @@ -211,7 +232,7 @@ private async Task ExecuteBulkOperationAsync( var tableIdentifier = _sqlGenerationHelper.DelimitIdentifier(tableName, schema); using var reader = bulkOperationContext.CreateReader(entitiesOrValues); - var numberOfAffectedRows = await ExecuteBulkOperationAsync(reader, bulkOperationContext, tableIdentifier, cancellationToken).ConfigureAwait(false); + var numberOfAffectedRows = await ExecuteBulkOperationAsync(reader, bulkOperationContext, tableIdentifier, returning, cancellationToken).ConfigureAwait(false); if (bulkOperationContext.HasExternalProperties) { @@ -245,7 +266,7 @@ private async Task ExecuteBulkOperationForSeparatedOwnedEntitiesAsync( { var tableName = tableNameProvider.GetValidTableName(childContext.EntityType); - numberOfAffectedRows += await ExecuteBulkOperationAsync(childContext.Entities, tableName.Schema, tableName.Name, childContext, tableNameProvider, cancellationToken).ConfigureAwait(false); + numberOfAffectedRows += await ExecuteBulkOperationAsync(childContext.Entities, tableName.Schema, tableName.Name, childContext, tableNameProvider, null, cancellationToken).ConfigureAwait(false); } return numberOfAffectedRows; @@ -255,11 +276,12 @@ private async Task ExecuteBulkOperationAsync( IEntityDataReader reader, ISqliteBulkOperationContext bulkOperationContext, string tableIdentifier, + SqliteReturning? returning, CancellationToken cancellationToken) { await using var command = bulkOperationContext.Connection.CreateCommand(); - command.CommandText = bulkOperationContext.CreateCommandBuilder().GetStatement(_sqlGenerationHelper, _stringBuilderPool, reader, tableIdentifier); + command.CommandText = bulkOperationContext.CreateCommandBuilder().GetStatement(_sqlGenerationHelper, _stringBuilderPool, reader, tableIdentifier, returning?.ColumnNames); var parameterInfos = CreateParameters(reader, command); try @@ -288,7 +310,21 @@ private async Task ExecuteBulkOperationAsync( paramInfo.Parameter.Value = value ?? DBNull.Value; } - numberOfAffectedRows += await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + if (returning is null) + { + numberOfAffectedRows += await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + } + else + { + await using var dataReader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false); + + // The statement returns no row if a conflicting row is not updated or if the key is not found. + while (await dataReader.ReadAsync(cancellationToken).ConfigureAwait(false)) + { + returning.Read(dataReader); + numberOfAffectedRows++; + } + } } stopwatch.Stop(); diff --git a/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteCommandBuilder.cs b/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteCommandBuilder.cs index dd7fcf77..8e4a281a 100644 --- a/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteCommandBuilder.cs +++ b/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteCommandBuilder.cs @@ -65,7 +65,24 @@ public abstract string GetStatement( ISqlGenerationHelper sqlGenerationHelper, ObjectPool stringBuilderPool, IEntityDataReader reader, - string tableIdentifier); + string tableIdentifier, + IReadOnlyList? returningColumns); + + private static void AppendReturning(StringBuilder sb, ISqlGenerationHelper sqlGenerationHelper, IReadOnlyList? returningColumns) + { + if (returningColumns is null) + return; + + sb.AppendLine().Append("RETURNING "); + + for (var i = 0; i < returningColumns.Count; i++) + { + if (i != 0) + sb.Append(", "); + + sb.Append(sqlGenerationHelper.DelimitIdentifier(returningColumns[i])); + } + } private class SqliteInsertBuilder : SqliteCommandBuilder { @@ -81,7 +98,8 @@ public override string GetStatement( ISqlGenerationHelper sqlGenerationHelper, ObjectPool stringBuilderPool, IEntityDataReader reader, - string tableIdentifier) + string tableIdentifier, + IReadOnlyList? returningColumns) { var sb = stringBuilderPool.Get(); @@ -89,6 +107,7 @@ public override string GetStatement( { GenerateInsertStatement(sb, sqlGenerationHelper, reader, tableIdentifier, _propertiesToInsert); + AppendReturning(sb, sqlGenerationHelper, returningColumns); sb.Append(sqlGenerationHelper.StatementTerminator); return sb.ToString(); @@ -117,7 +136,8 @@ public override string GetStatement( ISqlGenerationHelper sqlGenerationHelper, ObjectPool stringBuilderPool, IEntityDataReader reader, - string tableIdentifier) + string tableIdentifier, + IReadOnlyList? returningColumns) { var sb = stringBuilderPool.Get(); @@ -127,6 +147,7 @@ public override string GetStatement( GenerateSetAndWhereClause(sb, sqlGenerationHelper, reader, _propertiesToUpdate, _keyProperties); + AppendReturning(sb, sqlGenerationHelper, returningColumns); sb.Append(sqlGenerationHelper.StatementTerminator); return sb.ToString(); @@ -217,7 +238,8 @@ public override string GetStatement( ISqlGenerationHelper sqlGenerationHelper, ObjectPool stringBuilderPool, IEntityDataReader reader, - string tableIdentifier) + string tableIdentifier, + IReadOnlyList? returningColumns) { var sb = stringBuilderPool.Get(); @@ -256,6 +278,7 @@ public override string GetStatement( sb.Append("\tNOTHING"); } + AppendReturning(sb, sqlGenerationHelper, returningColumns); sb.Append(sqlGenerationHelper.StatementTerminator); return sb.ToString(); diff --git a/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteReturning.cs b/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteReturning.cs new file mode 100644 index 00000000..de7d1c36 --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteReturning.cs @@ -0,0 +1,34 @@ +using System.Data.Common; +using Thinktecture.EntityFrameworkCore.BulkOperations.Internal; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +/// +/// Collects the rows that the RETURNING clause of the statements of a bulk operation returns. +/// +internal abstract class SqliteReturning +{ + public abstract IReadOnlyList ColumnNames { get; } + + public abstract void Read(DbDataReader reader); +} + +internal sealed class SqliteReturning : SqliteReturning + where T : class +{ + private readonly BulkOperationReturningProjection _projection; + + public List Results { get; } = []; + + public override IReadOnlyList ColumnNames => _projection.ColumnNames; + + public SqliteReturning(BulkOperationReturningProjection projection) + { + _projection = projection; + } + + public override void Read(DbDataReader reader) + { + Results.Add(_projection.Read(reader)); + } +} diff --git a/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/Infrastructure/SqliteDbContextOptionsExtension.cs b/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/Infrastructure/SqliteDbContextOptionsExtension.cs index 6f722ddd..526c5225 100644 --- a/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/Infrastructure/SqliteDbContextOptionsExtension.cs +++ b/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/Infrastructure/SqliteDbContextOptionsExtension.cs @@ -139,6 +139,7 @@ public void ApplyServices(IServiceCollection services) services.TryAddScoped(provider => provider.GetRequiredService()); services.TryAddScoped(provider => provider.GetRequiredService()); services.TryAddScoped(provider => provider.GetRequiredService()); + services.TryAddScoped(provider => provider.GetRequiredService()); services.TryAddScoped(provider => provider.GetRequiredService()); } } diff --git a/tests/Thinktecture.EntityFrameworkCore.PostgreSQL.Tests/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutorTests/BulkOperationOutputAsync.cs b/tests/Thinktecture.EntityFrameworkCore.PostgreSQL.Tests/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutorTests/BulkOperationOutputAsync.cs new file mode 100644 index 00000000..7e14b708 --- /dev/null +++ b/tests/Thinktecture.EntityFrameworkCore.PostgreSQL.Tests/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutorTests/BulkOperationOutputAsync.cs @@ -0,0 +1,98 @@ +using Microsoft.EntityFrameworkCore.Infrastructure; +using Thinktecture.TestDatabaseContext; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations.NpgsqlBulkOperationExecutorTests; + +public class BulkOperationOutputAsync : IntegrationTestsBase +{ + private static readonly Guid _EXISTING_ID = new("79DA4171-C90B-4A5D-B0B5-D0A1E1BDF966"); + private static readonly Guid _NEW_ID = new("3DAEA618-B732-4BCA-A5A1-D1E075022DEC"); + + public BulkOperationOutputAsync(ITestOutputHelper testOutputHelper, NpgsqlFixture fixture) + : base(testOutputHelper, fixture) + { + } + + [Fact] + public async Task BulkInsertOrUpdate_should_return_the_inserted_and_the_updated_rows() + { + var existingEntity = new TestEntity { Id = _EXISTING_ID, RequiredName = "Old", Count = 1 }; + ArrangeDbContext.Add(existingEntity); + await ArrangeDbContext.SaveChangesAsync(); + + existingEntity.RequiredName = "New"; + existingEntity.Count = 2; + var newEntity = new TestEntity { Id = _NEW_ID, RequiredName = "Inserted", Count = 3 }; + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { existingEntity, newEntity }, + new NpgsqlBulkInsertOrUpdateOptions(), + row => new { row.Inserted.Id, row.Inserted.RequiredName, row.Inserted.Count }); + + result.Should().BeEquivalentTo(new[] + { + new { Id = _EXISTING_ID, RequiredName = "New", Count = 2 }, + new { Id = _NEW_ID, RequiredName = "Inserted", Count = 3 } + }); + } + + [Fact] + public async Task BulkInsertOrUpdate_should_return_the_whole_entity_including_converted_properties_and_fields() + { + var entity = new TestEntity { Id = _NEW_ID, Name = "Name", RequiredName = "RequiredName", Count = 3, ConvertibleClass = new ConvertibleClass(42), PropertyWithBackingField = 7 }; + entity.SetPrivateField(5); + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { entity }, new NpgsqlBulkInsertOrUpdateOptions(), row => row.Inserted); + + var inserted = result.Should().ContainSingle().Subject; + inserted.Should().BeEquivalentTo(entity, options => options.Excluding(e => e.Parent).Excluding(e => e.Children)); + inserted.GetPrivateField().Should().Be(5); + } + + [Fact] + public async Task BulkInsertOrUpdate_should_request_only_the_columns_that_the_projection_reads() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name", Count = 3 }; + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { entity }, new NpgsqlBulkInsertOrUpdateOptions(), row => row.Inserted.Count); + + result.Should().Equal(3); + + ExecutedCommands.Should().Contain(command => command.Contains("RETURNING \"Count\"", StringComparison.Ordinal)) + .And.NotContain(command => command.Contains("RETURNING \"Id\"", StringComparison.Ordinal)); + } + + [Fact] + public async Task BulkInsertOrUpdate_should_return_an_empty_list_if_entities_is_empty() + { + var result = await ActDbContext.BulkInsertOrUpdateAsync(new List(), new NpgsqlBulkInsertOrUpdateOptions(), row => row.Inserted.Id); + + result.Should().BeEmpty(); + } + + [Fact] + public async Task BulkUpdate_should_return_the_updated_rows_only() + { + var existingEntity = new TestEntity { Id = _EXISTING_ID, RequiredName = "Old", Count = 1 }; + ArrangeDbContext.Add(existingEntity); + await ArrangeDbContext.SaveChangesAsync(); + + existingEntity.Count = 2; + var missingEntity = new TestEntity { Id = _NEW_ID, RequiredName = "Missing", Count = 9 }; + + var result = await ActDbContext.BulkUpdateAsync(new[] { existingEntity, missingEntity }, + new NpgsqlBulkUpdateOptions(), + row => new { row.Inserted.Id, row.Inserted.Count }); + + result.Should().BeEquivalentTo(new[] { new { Id = _EXISTING_ID, Count = 2 } }); + } + + [Fact] + public async Task Should_throw_if_the_projection_reads_a_navigation() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name" }; + + await ActDbContext.Awaiting(ctx => ctx.BulkInsertOrUpdateAsync(new[] { entity }, new NpgsqlBulkInsertOrUpdateOptions(), row => row.Inserted.Parent)) + .Should().ThrowAsync() + .WithMessage("'Parent' is not a scalar property*"); + } +} \ No newline at end of file diff --git a/tests/Thinktecture.EntityFrameworkCore.Sqlite.Tests/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutorTests/BulkOperationOutputAsync.cs b/tests/Thinktecture.EntityFrameworkCore.Sqlite.Tests/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutorTests/BulkOperationOutputAsync.cs new file mode 100644 index 00000000..170a0659 --- /dev/null +++ b/tests/Thinktecture.EntityFrameworkCore.Sqlite.Tests/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutorTests/BulkOperationOutputAsync.cs @@ -0,0 +1,95 @@ +using Microsoft.EntityFrameworkCore.Infrastructure; +using Thinktecture.TestDatabaseContext; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations.SqliteBulkOperationExecutorTests; + +public class BulkOperationOutputAsync : IntegrationTestsBase +{ + private static readonly Guid _EXISTING_ID = new("79DA4171-C90B-4A5D-B0B5-D0A1E1BDF966"); + private static readonly Guid _NEW_ID = new("3DAEA618-B732-4BCA-A5A1-D1E075022DEC"); + + public BulkOperationOutputAsync(ITestOutputHelper testOutputHelper, DbContextProviderFactoryFixture fixture) + : base(testOutputHelper, fixture) + { + } + + [Fact] + public async Task BulkInsertOrUpdate_should_return_the_inserted_and_the_updated_rows() + { + var existingEntity = new TestEntity { Id = _EXISTING_ID, RequiredName = "Old", Count = 1 }; + ArrangeDbContext.Add(existingEntity); + await ArrangeDbContext.SaveChangesAsync(); + + existingEntity.RequiredName = "New"; + existingEntity.Count = 2; + var newEntity = new TestEntity { Id = _NEW_ID, RequiredName = "Inserted", Count = 3 }; + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { existingEntity, newEntity }, + new SqliteBulkInsertOrUpdateOptions(), + row => new { row.Inserted.Id, row.Inserted.RequiredName, row.Inserted.Count }); + + result.Should().BeEquivalentTo(new[] + { + new { Id = _EXISTING_ID, RequiredName = "New", Count = 2 }, + new { Id = _NEW_ID, RequiredName = "Inserted", Count = 3 } + }); + } + + [Fact] + public async Task BulkInsertOrUpdate_should_return_the_whole_entity_including_converted_properties_and_fields() + { + var entity = new TestEntity { Id = _NEW_ID, Name = "Name", RequiredName = "RequiredName", Count = 3, ConvertibleClass = new ConvertibleClass(42), PropertyWithBackingField = 7 }; + entity.SetPrivateField(5); + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { entity }, new SqliteBulkInsertOrUpdateOptions(), row => row.Inserted); + + var inserted = result.Should().ContainSingle().Subject; + inserted.Should().BeEquivalentTo(entity, options => options.Excluding(e => e.Parent).Excluding(e => e.Children)); + inserted.GetPrivateField().Should().Be(5); + } + + [Fact] + public async Task BulkInsertOrUpdate_should_request_only_the_columns_that_the_projection_reads() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name", Count = 3 }; + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { entity }, new SqliteBulkInsertOrUpdateOptions(), row => row.Inserted.Count); + + result.Should().Equal(3); + } + + [Fact] + public async Task BulkInsertOrUpdate_should_return_an_empty_list_if_entities_is_empty() + { + var result = await ActDbContext.BulkInsertOrUpdateAsync(new List(), new SqliteBulkInsertOrUpdateOptions(), row => row.Inserted.Id); + + result.Should().BeEmpty(); + } + + [Fact] + public async Task BulkUpdate_should_return_the_updated_rows_only() + { + var existingEntity = new TestEntity { Id = _EXISTING_ID, RequiredName = "Old", Count = 1 }; + ArrangeDbContext.Add(existingEntity); + await ArrangeDbContext.SaveChangesAsync(); + + existingEntity.Count = 2; + var missingEntity = new TestEntity { Id = _NEW_ID, RequiredName = "Missing", Count = 9 }; + + var result = await ActDbContext.BulkUpdateAsync(new[] { existingEntity, missingEntity }, + new SqliteBulkUpdateOptions(), + row => new { row.Inserted.Id, row.Inserted.Count }); + + result.Should().BeEquivalentTo(new[] { new { Id = _EXISTING_ID, Count = 2 } }); + } + + [Fact] + public async Task Should_throw_if_the_projection_reads_a_navigation() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name" }; + + await ActDbContext.Awaiting(ctx => ctx.BulkInsertOrUpdateAsync(new[] { entity }, new SqliteBulkInsertOrUpdateOptions(), row => row.Inserted.Parent)) + .Should().ThrowAsync() + .WithMessage("'Parent' is not a scalar property*"); + } +} \ No newline at end of file From 4cb575686fa30d0c07bc0367f22fd4c97d62f823 Mon Sep 17 00:00:00 2001 From: pengweiqhca Date: Thu, 3 Dec 2026 17:57:34 +0800 Subject: [PATCH 4/7] Support the provider independent BulkOperationOutput projection on SQL Server SqlServerBulkOperationExecutor implements IBulkOperationOutputExecutor, so DbContext.BulkInsertOrUpdateAsync and DbContext.BulkUpdateAsync with a BulkOperationOutput 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 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. --- ...ServerBulkOperationExecutor.MergeOutput.cs | 61 ++++++++++++++++++- .../SqlServerDbContextOptionsExtension.cs | 1 + .../MergeOutput.cs | 48 +++++++++++++++ 3 files changed, 109 insertions(+), 1 deletion(-) diff --git a/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.MergeOutput.cs b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.MergeOutput.cs index b6a9a0ae..9fecb964 100644 --- a/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.MergeOutput.cs +++ b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.MergeOutput.cs @@ -4,7 +4,7 @@ namespace Thinktecture.EntityFrameworkCore.BulkOperations; -public sealed partial class SqlServerBulkOperationExecutor +public sealed partial class SqlServerBulkOperationExecutor : IBulkOperationOutputExecutor { /// /// Updates existing rows and inserts the missing ones (MERGE) and returns the OUTPUT rows selected by . @@ -62,6 +62,65 @@ public async Task> BulkUpdateAsync( return await BulkUpdateAsync(entities, options, plan.Sql, (statement, token) => ExecuteMergeAsync(plan, statement, token), cancellationToken); } + /// + Task> IBulkOperationOutputExecutor.BulkInsertOrUpdateAsync( + IEnumerable entities, + IBulkInsertOrUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(options); + + if (options is not SqlServerBulkInsertOrUpdateOptions sqlServerOptions) + sqlServerOptions = new SqlServerBulkInsertOrUpdateOptions(options); + + return BulkInsertOrUpdateAsync(entities, sqlServerOptions, ToMergeOutput(output), cancellationToken); + } + + /// + Task> IBulkOperationOutputExecutor.BulkUpdateAsync( + IEnumerable entities, + IBulkUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(options); + + if (options is not SqlServerBulkUpdateOptions sqlServerOptions) + sqlServerOptions = new SqlServerBulkUpdateOptions(options); + + return BulkUpdateAsync(entities, sqlServerOptions, ToMergeOutput(output), cancellationToken); + } + + // BulkOperationOutput offers "Inserted" only, which SqlServerMergeOutput offers as well. + private static Expression, TResult>> ToMergeOutput(Expression, TResult>> output) + where T : class + { + ArgumentNullException.ThrowIfNull(output); + + var mergeOutput = Expression.Parameter(typeof(SqlServerMergeOutput), output.Parameters[0].Name); + var body = new InsertedRewriter(output.Parameters[0], mergeOutput).Visit(output.Body); + + return Expression.Lambda, TResult>>(body, mergeOutput); + } + + private sealed class InsertedRewriter(ParameterExpression from, ParameterExpression to) : ExpressionVisitor + { + protected override Expression VisitMember(MemberExpression node) + { + return node.Expression == from + ? Expression.Property(to, nameof(SqlServerMergeOutput<>.Inserted)) + : base.VisitMember(node); + } + + protected override Expression VisitParameter(ParameterExpression node) + { + return node == from + ? throw new NotSupportedException("The projection must read the properties of the 'Inserted' member of the output row, the output row itself cannot be used on SQL Server.") + : node; + } + } + private Task> ExecuteMergeAsync( SqlServerMergeOutputPlan plan, string mergeStatement, diff --git a/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/Infrastructure/SqlServerDbContextOptionsExtension.cs b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/Infrastructure/SqlServerDbContextOptionsExtension.cs index 2f460236..87ed4cb7 100644 --- a/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/Infrastructure/SqlServerDbContextOptionsExtension.cs +++ b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/Infrastructure/SqlServerDbContextOptionsExtension.cs @@ -163,6 +163,7 @@ public void ApplyServices(IServiceCollection services) services.TryAddScoped(provider => provider.GetRequiredService()); services.TryAddScoped(provider => provider.GetRequiredService()); services.TryAddScoped(provider => provider.GetRequiredService()); + services.TryAddScoped(provider => provider.GetRequiredService()); services.TryAddScoped(provider => provider.GetRequiredService()); } diff --git a/tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutorTests/MergeOutput.cs b/tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutorTests/MergeOutput.cs index 3293a7cd..7b721894 100644 --- a/tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutorTests/MergeOutput.cs +++ b/tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutorTests/MergeOutput.cs @@ -100,6 +100,54 @@ public async Task Should_return_updated_rows_of_BulkUpdate() result.Should().BeEquivalentTo(new[] { new { Id = _EXISTING_ID, Count = 2, OldCount = 1, Action = SqlServerMergeAction.Update } }); } + [Fact] + public async Task Should_support_the_provider_independent_BulkOperationOutput_for_BulkInsertOrUpdate() + { + var existingEntity = new TestEntity { Id = _EXISTING_ID, RequiredName = "Old", Count = 1 }; + ArrangeDbContext.Add(existingEntity); + await ArrangeDbContext.SaveChangesAsync(); + + existingEntity.Count = 2; + var newEntity = new TestEntity { Id = _NEW_ID, RequiredName = "Inserted", Count = 3 }; + + // The options are typed as the interface, so the overload of BulkOperationOutput is selected. + IBulkInsertOrUpdateOptions options = new SqlServerBulkInsertOrUpdateOptions(); + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { existingEntity, newEntity }, options, row => new { row.Inserted.Id, row.Inserted.Count }); + + result.Should().BeEquivalentTo(new[] + { + new { Id = _EXISTING_ID, Count = 2 }, + new { Id = _NEW_ID, Count = 3 } + }); + } + + [Fact] + public async Task Should_support_the_provider_independent_BulkOperationOutput_for_BulkUpdate() + { + var existingEntity = new TestEntity { Id = _EXISTING_ID, RequiredName = "Old", Count = 1 }; + ArrangeDbContext.Add(existingEntity); + await ArrangeDbContext.SaveChangesAsync(); + + existingEntity.Count = 2; + var missingEntity = new TestEntity { Id = _NEW_ID, RequiredName = "Missing", Count = 9 }; + + IBulkUpdateOptions options = new SqlServerBulkUpdateOptions(); + var result = await ActDbContext.BulkUpdateAsync(new[] { existingEntity, missingEntity }, options, row => row.Inserted); + + result.Should().ContainSingle().Which.Should().BeEquivalentTo(existingEntity, o => o.Excluding(e => e.Parent).Excluding(e => e.Children)); + } + + [Fact] + public async Task Should_throw_if_the_provider_independent_projection_uses_the_output_row_as_a_whole() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name" }; + IBulkInsertOrUpdateOptions options = new SqlServerBulkInsertOrUpdateOptions(); + + await ActDbContext.Awaiting(ctx => ctx.BulkInsertOrUpdateAsync(new[] { entity }, options, row => row)) + .Should().ThrowAsync() + .WithMessage("The projection must read the properties of the 'Inserted' member*"); + } + [Fact] public async Task Should_return_an_empty_list_if_entities_is_empty() { From d5c2ed412f25dae9d767b85507ebaba6ed6a0dee Mon Sep 17 00:00:00 2001 From: pengweiqhca Date: Thu, 3 Dec 2026 20:23:39 +0800 Subject: [PATCH 5/7] Materialize the returned rows by the stored discriminator and reset properties 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. --- .../Internal/BulkOperationOutputMapper.cs | 266 ++++++++++++++++++ .../BulkOperationReturningProjection.cs | 98 +------ .../SqlServerMergeOutputPlan.cs | 195 ++++--------- .../BulkOperationOutputAsync.cs | 60 +++- .../MergeOutput.cs | 80 ++++++ .../BulkOperationOutputAsync.cs | 60 +++- 6 files changed, 527 insertions(+), 232 deletions(-) create mode 100644 src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationOutputMapper.cs diff --git a/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationOutputMapper.cs b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationOutputMapper.cs new file mode 100644 index 00000000..90a46982 --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationOutputMapper.cs @@ -0,0 +1,266 @@ +using System.Data.Common; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations.Internal; + +/// +/// Describes a column that a bulk operation returns from the database. +/// This is an internal API. It may be changed or removed without notice. +/// +/// The name of the column. +/// The store type of the column. +public readonly record struct BulkOperationOutputColumn(string ColumnName, string StoreType); + +/// +/// Materializes the entities of the rows that a bulk operation returns from the database. +/// This is an internal API. It may be changed or removed without notice. +/// +/// +/// The columns are the properties that the projection reads, followed by the discriminator column if the entity type has derived types. +/// The discriminator decides which type is created, because the type that is stored in the database can differ from the type of the input. +/// A database NULL resets the property, so values that the constructor assigned do not survive. +/// +/// Type of the entity. +public sealed class BulkOperationOutputMapper + where T : class +{ + private readonly Column[] _columns; + private readonly int _discriminatorIndex; + private readonly Dictionary _concreteTypes; + private readonly ConcreteType _fallback; + + /// + /// The columns to return, in the order in which reads them. + /// + public IReadOnlyList Columns { get; } + + private BulkOperationOutputMapper(Column[] columns, int discriminatorIndex, Dictionary concreteTypes, ConcreteType fallback) + { + _columns = columns; + _discriminatorIndex = discriminatorIndex; + _concreteTypes = concreteTypes; + _fallback = fallback; + Columns = columns.Select(static column => new BulkOperationOutputColumn(column.ColumnName, column.StoreType)).ToList(); + } + + /// + /// Creates the mapper. + /// + /// The entity type of the table. + /// The table. + /// Indication whether all properties are read, i.e. the projection uses the whole entity. + /// The names of the properties that the projection reads. + /// The mapper. + /// A member is not a scalar property that is mapped to a column of the table. + public static BulkOperationOutputMapper Create( + IEntityType entityType, + StoreObjectIdentifier storeObject, + bool all, + IReadOnlyCollection memberNames) + { + ArgumentNullException.ThrowIfNull(entityType); + ArgumentNullException.ThrowIfNull(memberNames); + + // The members are validated even if the whole entity is read, so that a projection like "new { Entity = row.Inserted, row.Inserted.Parent }" is rejected. + var members = memberNames.Select(name => entityType.FindProperty(name) is { } property && property.GetColumnName(storeObject) is not null + ? property + : throw new NotSupportedException($"'{name}' is not a scalar property of the entity '{entityType.DisplayName()}' that is mapped to a column of table '{storeObject.Name}'. Only such properties can be selected from the returned row.")) + .ToList(); + + var properties = all + ? GetAllProperties(entityType, storeObject) + : members; + + var discriminator = entityType.GetDerivedTypes().Any() ? entityType.FindDiscriminatorProperty() : null; + var columns = properties.Select(property => new Column(property, storeObject, requireSetter: true)).ToList(); + var discriminatorIndex = -1; + + if (discriminator is not null) + { + discriminatorIndex = properties.IndexOf(discriminator); + + if (discriminatorIndex < 0) + { + discriminatorIndex = columns.Count; + columns.Add(new Column(discriminator, storeObject, requireSetter: false)); + } + } + + var concreteTypes = new Dictionary(); + var hierarchy = entityType.GetDerivedTypesInclusive().Where(static type => !type.IsAbstract()).ToList(); + + ConcreteType? fallback = null; + + foreach (var type in hierarchy) + { + var concreteType = new ConcreteType(type, columns.Select(column => column.IsDeclaredOn(type)).ToArray()); + fallback ??= concreteType; + + if (type == entityType) + fallback = concreteType; + + if (discriminator is not null && type.GetDiscriminatorValue() is { } value) + concreteTypes[value] = concreteType; + } + + return new BulkOperationOutputMapper(columns.ToArray(), + discriminatorIndex, + concreteTypes, + fallback ?? throw new InvalidOperationException($"The entity type '{entityType.DisplayName()}' and its derived types are abstract, so no entity can be created.")); + } + + /// + /// Reads an entity from the current row of . + /// + /// The reader, positioned on a row. + /// The ordinal of the first column of the entity. + /// The entity. + public T Read(DbDataReader reader, int firstOrdinal) + { + ArgumentNullException.ThrowIfNull(reader); + + var concreteType = GetConcreteType(reader, firstOrdinal); + var entity = concreteType.Create(); + + for (var i = 0; i < _columns.Length; i++) + { + if (!concreteType.IsColumnOfType[i]) + continue; + + _columns[i].Apply(entity, reader, firstOrdinal + i); + } + + return (T)entity; + } + + private ConcreteType GetConcreteType(DbDataReader reader, int firstOrdinal) + { + if (_discriminatorIndex < 0) + return _fallback; + + var column = _columns[_discriminatorIndex]; + + // The deleted columns of an inserted row are NULL. + if (reader.IsDBNull(firstOrdinal + _discriminatorIndex)) + return _fallback; + + var value = column.ReadValue(reader, firstOrdinal + _discriminatorIndex)!; + + return _concreteTypes.TryGetValue(value, out var concreteType) + ? concreteType + : throw new InvalidOperationException($"The discriminator value '{value}' returned by the database does not belong to an entity type of the hierarchy of '{typeof(T).Name}'."); + } + + private static List GetAllProperties(IEntityType entityType, StoreObjectIdentifier storeObject) + { + return entityType.GetProperties() + .Concat(entityType.GetDerivedTypes().SelectMany(static type => type.GetDeclaredProperties())) + .Where(property => !property.IsShadowProperty() && property.GetColumnName(storeObject) is not null) + .ToList(); + } + + private sealed class ConcreteType + { + private readonly Func _create; + + // Indication per column whether the property belongs to this type, i.e. the property is declared on the type or on one of its base types. + public bool[] IsColumnOfType { get; } + + public ConcreteType(IEntityType entityType, bool[] isColumnOfType) + { + IsColumnOfType = isColumnOfType; + + var constructor = entityType.ClrType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Type.EmptyTypes); + + // The properties that are not read keep their default values, so the constructor is not required. + _create = constructor is null + ? () => RuntimeHelpers.GetUninitializedObject(entityType.ClrType) + : Expression.Lambda>(Expression.Convert(Expression.New(constructor), typeof(object))).Compile(); + } + + public object Create() => _create(); + } + + private sealed class Column + { + private readonly IProperty _property; + private readonly ValueConverter? _converter; + private readonly Func _read; + private readonly Action? _setter; + private readonly object? _nullValue; + + public string ColumnName { get; } + public string StoreType { get; } + + public Column(IProperty property, StoreObjectIdentifier storeObject, bool requireSetter) + { + var typeMapping = property.GetRelationalTypeMapping(); + + _property = property; + _converter = typeMapping.Converter; + _read = CreateReader(typeMapping); + _setter = CreateSetter(property); + + if (_setter is null && requireSetter) + throw new InvalidOperationException($"The property '{property.DeclaringType.DisplayName()}.{property.Name}' has neither a setter nor a backing field, so it cannot be selected from the returned row."); + + // A reference type and a nullable value type are reset to null, any other value type to its default value. + _nullValue = property.ClrType.IsValueType && Nullable.GetUnderlyingType(property.ClrType) is null + ? Activator.CreateInstance(property.ClrType) + : null; + + ColumnName = property.GetColumnName(storeObject)!; + StoreType = property.GetColumnType(storeObject) ?? typeMapping.StoreType; + } + + public bool IsDeclaredOn(IEntityType entityType) + { + return _property.DeclaringType is IEntityType declaringType && declaringType.IsAssignableFrom(entityType); + } + + public object? ReadValue(DbDataReader reader, int ordinal) + { + var value = _read(reader, ordinal); + + return _converter is null ? value : _converter.ConvertFromProvider(value); + } + + public void Apply(object entity, DbDataReader reader, int ordinal) + { + // The discriminator is selected to find the type. It is a shadow property if it has no setter. + if (_setter is null) + return; + + _setter(entity, reader.IsDBNull(ordinal) ? _nullValue : ReadValue(reader, ordinal)); + } + + // The setter or the backing field may be private, the setter may be init-only. + private static Action? CreateSetter(IProperty property) + { + if (property.PropertyInfo?.SetMethod is { } setMethod) + { + var instance = Expression.Parameter(typeof(object)); + var value = Expression.Parameter(typeof(object)); + var call = Expression.Call(Expression.Convert(instance, setMethod.DeclaringType!), setMethod, Expression.Convert(value, setMethod.GetParameters()[0].ParameterType)); + + return Expression.Lambda>(call, instance, value).Compile(); + } + + return property.FieldInfo is { } field ? field.SetValue : null; + } + + private static Func CreateReader(RelationalTypeMapping typeMapping) + { + var reader = Expression.Parameter(typeof(DbDataReader)); + var ordinal = Expression.Parameter(typeof(int)); + var call = Expression.Call(reader, typeMapping.GetDataReaderMethod(), ordinal); + + return Expression.Lambda>(Expression.Convert(call, typeof(object)), reader, ordinal).Compile(); + } + } +} diff --git a/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationReturningProjection.cs b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationReturningProjection.cs index bbb14720..a5fe5ee2 100644 --- a/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationReturningProjection.cs +++ b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationReturningProjection.cs @@ -1,9 +1,7 @@ using System.Data.Common; using System.Linq.Expressions; -using System.Runtime.CompilerServices; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Thinktecture.EntityFrameworkCore.BulkOperations.Internal; @@ -16,21 +14,19 @@ namespace Thinktecture.EntityFrameworkCore.BulkOperations.Internal; public sealed class BulkOperationReturningProjection where T : class { - private readonly Column[] _columns; + private readonly BulkOperationOutputMapper _mapper; private readonly Func, TResult> _projection; - private readonly Func _createEntity; /// /// The names of the columns to return, in the order in which reads them. /// public IReadOnlyList ColumnNames { get; } - private BulkOperationReturningProjection(Column[] columns, Func, TResult> projection, Func createEntity) + private BulkOperationReturningProjection(BulkOperationOutputMapper mapper, Func, TResult> projection) { - _columns = columns; + _mapper = mapper; _projection = projection; - _createEntity = createEntity; - ColumnNames = columns.Select(static column => column.ColumnName).ToList(); + ColumnNames = mapper.Columns.Select(static column => column.ColumnName).ToList(); } /// @@ -51,18 +47,13 @@ public static BulkOperationReturningProjection Create(IEntityType en var collector = new MemberCollector(output.Parameters[0]); collector.Visit(output.Body); - var properties = collector.All - ? entityType.GetProperties().Where(property => !property.IsShadowProperty() && property.GetColumnName(storeObject) is not null).ToList() - : collector.Members.Select(name => entityType.FindProperty(name) is { } property && property.GetColumnName(storeObject) is not null - ? property - : throw new NotSupportedException($"'{name}' is not a scalar property of the entity '{entityType.DisplayName()}' that is mapped to a column of table '{storeObject.Name}'. Only such properties can be selected from the RETURNING clause.")) - .ToList(); + var members = collector.Members; // A statement without a column to return is invalid. The projection reads nothing from the row, so any column is good enough. - if (properties.Count == 0) - properties.Add(entityType.FindPrimaryKey()?.Properties[0] ?? entityType.GetProperties().First(property => property.GetColumnName(storeObject) is not null)); + if (members.Count == 0 && !collector.All) + members = [(entityType.FindPrimaryKey()?.Properties[0] ?? entityType.GetProperties().First(property => property.GetColumnName(storeObject) is not null)).Name]; - return new BulkOperationReturningProjection(properties.Select(property => new Column(property, storeObject)).ToArray(), output.Compile(), CreateEntityFactory()); + return new BulkOperationReturningProjection(BulkOperationOutputMapper.Create(entityType, storeObject, collector.All, members), output.Compile()); } /// @@ -74,24 +65,7 @@ public TResult Read(DbDataReader reader) { ArgumentNullException.ThrowIfNull(reader); - var row = new BulkOperationOutput { Inserted = _createEntity() }; - - for (var i = 0; i < _columns.Length; i++) - { - // A NULL keeps the default of the property. - if (reader.IsDBNull(i)) - continue; - - var column = _columns[i]; - var value = column.Read(reader, i); - - if (column.Converter is not null) - value = column.Converter.ConvertFromProvider(value); - - column.Setter(row.Inserted, value); - } - - return _projection(row); + return _projection(new BulkOperationOutput { Inserted = _mapper.Read(reader, 0) }); } /// @@ -114,60 +88,6 @@ public async Task> ReadAllAsync(DbDataReader reader, CancellationT return results; } - private static Func CreateEntityFactory() - { - var constructor = typeof(T).GetConstructor(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic, Type.EmptyTypes); - - // The properties that are not selected keep their default values, so the constructor is not required. - return constructor is null || typeof(T).IsAbstract - ? static () => (T)RuntimeHelpers.GetUninitializedObject(typeof(T)) - : Expression.Lambda>(Expression.New(constructor)).Compile(); - } - - private sealed class Column - { - public string ColumnName { get; } - public ValueConverter? Converter { get; } - public Func Read { get; } - public Action Setter { get; } - - public Column(IProperty property, StoreObjectIdentifier storeObject) - { - var typeMapping = property.GetRelationalTypeMapping(); - - ColumnName = property.GetColumnName(storeObject)!; - Converter = typeMapping.Converter; - Read = CreateReader(typeMapping); - Setter = CreateSetter(property); - } - - // The setter or the backing field may be private, the setter may be init-only. - private static Action CreateSetter(IProperty property) - { - if (property.PropertyInfo?.SetMethod is { } setMethod) - { - var instance = Expression.Parameter(typeof(object)); - var value = Expression.Parameter(typeof(object)); - var call = Expression.Call(Expression.Convert(instance, setMethod.DeclaringType!), setMethod, Expression.Convert(value, setMethod.GetParameters()[0].ParameterType)); - - return Expression.Lambda>(call, instance, value).Compile(); - } - - var field = property.FieldInfo ?? throw new InvalidOperationException($"The property '{property.DeclaringType.DisplayName()}.{property.Name}' has neither a setter nor a backing field, so it cannot be selected from the RETURNING clause."); - - return field.SetValue; - } - - private static Func CreateReader(RelationalTypeMapping typeMapping) - { - var reader = Expression.Parameter(typeof(DbDataReader)); - var ordinal = Expression.Parameter(typeof(int)); - var call = Expression.Call(reader, typeMapping.GetDataReaderMethod(), ordinal); - - return Expression.Lambda>(Expression.Convert(call, typeof(object)), reader, ordinal).Compile(); - } - } - // Collects the members of "output.Inserted" that the projection reads. private sealed class MemberCollector(ParameterExpression parameter) : ExpressionVisitor { diff --git a/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeOutputPlan.cs b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeOutputPlan.cs index 9a88ab82..ceabc0a4 100644 --- a/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeOutputPlan.cs +++ b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeOutputPlan.cs @@ -1,10 +1,9 @@ using System.Data.Common; -using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; using System.Text; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Thinktecture.EntityFrameworkCore.BulkOperations.Internal; namespace Thinktecture.EntityFrameworkCore.BulkOperations; @@ -21,33 +20,32 @@ internal sealed record SqlServerMergeOutputSql(string Declaration, string Output /// /// /// The rows are written into a table variable first (OUTPUT ... INTO), because SQL Server rejects OUTPUT without INTO if the target table has enabled triggers. +/// The columns of the table variable are the action, the columns of inserted and the columns of deleted, in this order. /// -[SuppressMessage("Usage", "EF1001:Internal EF Core API usage.")] internal sealed class SqlServerMergeOutputPlan where T : class { private const string _TABLE_VARIABLE = "@MergeOutput"; private const string _ACTION_COLUMN = "Action"; - private readonly OutputColumn[] _columns; + private readonly BulkOperationOutputMapper? _inserted; + private readonly BulkOperationOutputMapper? _deleted; + private readonly int _deletedOrdinal; private readonly Func, TResult> _projection; - private readonly Func _createEntity; - private readonly bool _usesInserted; - private readonly bool _usesDeleted; public SqlServerMergeOutputSql Sql { get; } private SqlServerMergeOutputPlan( - OutputColumn[] columns, + BulkOperationOutputMapper? inserted, + BulkOperationOutputMapper? deleted, Func, TResult> projection, - Func createEntity, SqlServerMergeOutputSql sql) { - _columns = columns; + _inserted = inserted; + _deleted = deleted; + // The first column is the action. + _deletedOrdinal = 1 + (inserted?.Columns.Count ?? 0); _projection = projection; - _createEntity = createEntity; - _usesInserted = columns.Any(static column => column.IsInserted); - _usesDeleted = columns.Any(static column => !column.IsInserted); Sql = sql; } @@ -62,15 +60,10 @@ public static SqlServerMergeOutputPlan Create( var collector = new MemberCollector(output.Parameters[0]); collector.Visit(output.Body); - var columns = new List(); - AddColumns(columns, entityType, storeObject, isInserted: true, collector.AllInserted, collector.InsertedMembers); - AddColumns(columns, entityType, storeObject, isInserted: false, collector.AllDeleted, collector.DeletedMembers); + var inserted = collector.UsesInserted ? BulkOperationOutputMapper.Create(entityType, storeObject, collector.AllInserted, collector.InsertedMembers) : null; + var deleted = collector.UsesDeleted ? BulkOperationOutputMapper.Create(entityType, storeObject, collector.AllDeleted, collector.DeletedMembers) : null; - return new SqlServerMergeOutputPlan( - columns.ToArray(), - output.Compile(), - CreateEntityFactory(), - CreateSql(sqlGenerationHelper, columns)); + return new SqlServerMergeOutputPlan(inserted, deleted, output.Compile(), CreateSql(sqlGenerationHelper, inserted, deleted)); } public async Task> ReadAsync(DbDataReader reader, CancellationToken cancellationToken) @@ -81,25 +74,11 @@ public async Task> ReadAsync(DbDataReader reader, CancellationToke { var row = new SqlServerMergeOutput { Action = ParseAction(reader.GetString(0)) }; - if (_usesInserted) - row.Inserted = _createEntity(); + if (_inserted is not null) + row.Inserted = _inserted.Read(reader, 1); - if (_usesDeleted) - row.Deleted = _createEntity(); - - foreach (var column in _columns) - { - // A NULL keeps the default of the property: the deleted columns of an inserted row are NULL. - if (reader.IsDBNull(column.Ordinal)) - continue; - - var value = column.Read(reader, column.Ordinal); - - if (column.Converter is not null) - value = column.Converter.ConvertFromProvider(value); - - column.Setter(column.IsInserted ? row.Inserted : row.Deleted, value); - } + if (_deleted is not null) + row.Deleted = _deleted.Read(reader, _deletedOrdinal); results.Add(_projection(row)); } @@ -117,45 +96,10 @@ private static SqlServerMergeAction ParseAction(string action) }; } - private static void AddColumns( - List columns, - IEntityType entityType, - StoreObjectIdentifier storeObject, - bool isInserted, - bool all, - HashSet memberNames) - { - IEnumerable properties; - - if (all) - { - properties = entityType.GetProperties().Where(property => !property.IsShadowProperty() && property.GetColumnName(storeObject) is not null); - } - else - { - properties = memberNames.Select(name => entityType.FindProperty(name) is { } property && property.GetColumnName(storeObject) is not null - ? property - : throw new NotSupportedException($"'{name}' is not a scalar property of the entity '{entityType.DisplayName()}' that is mapped to a column of table '{storeObject.Name}'. Only such properties can be selected from the OUTPUT clause.")); - } - - foreach (var property in properties) - { - // The first column of the result is the action. - columns.Add(new OutputColumn(isInserted, property, storeObject, columns.Count + 1)); - } - } - - private static Func CreateEntityFactory() - { - var constructor = typeof(T).GetConstructor(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic, Type.EmptyTypes); - - // The properties that are not selected keep their default values, so the constructor is not required. - return constructor is null || typeof(T).IsAbstract - ? static () => (T)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(T)) - : Expression.Lambda>(Expression.New(constructor)).Compile(); - } - - private static SqlServerMergeOutputSql CreateSql(ISqlGenerationHelper sqlGenerationHelper, List columns) + private static SqlServerMergeOutputSql CreateSql( + ISqlGenerationHelper sqlGenerationHelper, + BulkOperationOutputMapper? inserted, + BulkOperationOutputMapper? deleted) { var action = sqlGenerationHelper.DelimitIdentifier(_ACTION_COLUMN); @@ -163,15 +107,22 @@ private static SqlServerMergeOutputSql CreateSql(ISqlGenerationHelper sqlGenerat var output = new StringBuilder("OUTPUT $action"); var into = new StringBuilder(action); var select = new StringBuilder("SELECT ").Append(action); + var ordinal = 1; - foreach (var column in columns) + foreach (var (mapper, prefix, alias) in new[] { (inserted, "inserted.", 'i'), (deleted, "deleted.", 'd') }) { - var name = sqlGenerationHelper.DelimitIdentifier(column.Name); + if (mapper is null) + continue; - declaration.Append(", ").Append(name).Append(' ').Append(column.StoreType).Append(" NULL"); - output.Append(", ").Append(column.IsInserted ? "inserted." : "deleted.").Append(sqlGenerationHelper.DelimitIdentifier(column.ColumnName)); - into.Append(", ").Append(name); - select.Append(", ").Append(name); + foreach (var column in mapper.Columns) + { + var name = sqlGenerationHelper.DelimitIdentifier($"{alias}{ordinal++}"); + + declaration.Append(", ").Append(name).Append(' ').Append(GetStoreType(column.StoreType)).Append(" NULL"); + output.Append(", ").Append(prefix).Append(sqlGenerationHelper.DelimitIdentifier(column.ColumnName)); + into.Append(", ").Append(name); + select.Append(", ").Append(name); + } } return new SqlServerMergeOutputSql( @@ -180,64 +131,12 @@ private static SqlServerMergeOutputSql CreateSql(ISqlGenerationHelper sqlGenerat select.Append(" FROM ").Append(_TABLE_VARIABLE).Append(';').ToString()); } - private sealed class OutputColumn + // A rowversion/timestamp column cannot receive an explicit value. + private static string GetStoreType(string storeType) { - public bool IsInserted { get; } - public int Ordinal { get; } - public string Name { get; } - public string ColumnName { get; } - public string StoreType { get; } - public ValueConverter? Converter { get; } - public Func Read { get; } - public Action Setter { get; } - - public OutputColumn(bool isInserted, IProperty property, StoreObjectIdentifier storeObject, int ordinal) - { - var typeMapping = property.GetRelationalTypeMapping(); - - IsInserted = isInserted; - Ordinal = ordinal; - Name = $"{(isInserted ? 'i' : 'd')}{ordinal}"; - ColumnName = property.GetColumnName(storeObject)!; - StoreType = GetStoreType(property.GetColumnType(storeObject) ?? typeMapping.StoreType); - Converter = typeMapping.Converter; - Read = CreateReader(typeMapping); - Setter = CreateSetter(property); - } - - // A rowversion/timestamp column cannot receive an explicit value. - private static string GetStoreType(string storeType) - { - return storeType.Equals("rowversion", StringComparison.OrdinalIgnoreCase) || storeType.Equals("timestamp", StringComparison.OrdinalIgnoreCase) - ? "binary(8)" - : storeType; - } - - // The setter or the backing field may be private, the setter may be init-only. - private static Action CreateSetter(IProperty property) - { - if (property.PropertyInfo?.SetMethod is { } setMethod) - { - var instance = Expression.Parameter(typeof(object)); - var value = Expression.Parameter(typeof(object)); - var call = Expression.Call(Expression.Convert(instance, setMethod.DeclaringType!), setMethod, Expression.Convert(value, setMethod.GetParameters()[0].ParameterType)); - - return Expression.Lambda>(call, instance, value).Compile(); - } - - var field = property.FieldInfo ?? throw new InvalidOperationException($"The property '{property.DeclaringType.DisplayName()}.{property.Name}' has neither a setter nor a backing field, so it cannot be selected from the OUTPUT clause."); - - return field.SetValue; - } - - private static Func CreateReader(RelationalTypeMapping typeMapping) - { - var reader = Expression.Parameter(typeof(DbDataReader)); - var ordinal = Expression.Parameter(typeof(int)); - var call = Expression.Call(reader, typeMapping.GetDataReaderMethod(), ordinal); - - return Expression.Lambda>(Expression.Convert(call, typeof(object)), reader, ordinal).Compile(); - } + return storeType.Equals("rowversion", StringComparison.OrdinalIgnoreCase) || storeType.Equals("timestamp", StringComparison.OrdinalIgnoreCase) + ? "binary(8)" + : storeType; } // Collects the members of "output.Inserted" and "output.Deleted" that the projection reads. @@ -247,6 +146,8 @@ private sealed class MemberCollector(ParameterExpression parameter) : Expression public HashSet DeletedMembers { get; } = []; public bool AllInserted { get; private set; } public bool AllDeleted { get; private set; } + public bool UsesInserted { get; private set; } + public bool UsesDeleted { get; private set; } protected override Expression VisitMember(MemberExpression node) { @@ -254,6 +155,7 @@ protected override Expression VisitMember(MemberExpression node) if (IsSide(node.Expression, out var isInserted)) { (isInserted ? InsertedMembers : DeletedMembers).Add(node.Member.Name); + Use(isInserted); return node; } @@ -265,6 +167,7 @@ protected override Expression VisitMember(MemberExpression node) else AllDeleted = true; + Use(isInserted); return node; } @@ -282,11 +185,21 @@ protected override Expression VisitParameter(ParameterExpression node) { AllInserted = true; AllDeleted = true; + UsesInserted = true; + UsesDeleted = true; } return node; } + private void Use(bool isInserted) + { + if (isInserted) + UsesInserted = true; + else + UsesDeleted = true; + } + private bool IsSide(Expression? expression, out bool isInserted) { isInserted = false; diff --git a/tests/Thinktecture.EntityFrameworkCore.PostgreSQL.Tests/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutorTests/BulkOperationOutputAsync.cs b/tests/Thinktecture.EntityFrameworkCore.PostgreSQL.Tests/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutorTests/BulkOperationOutputAsync.cs index 7e14b708..50df0f5e 100644 --- a/tests/Thinktecture.EntityFrameworkCore.PostgreSQL.Tests/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutorTests/BulkOperationOutputAsync.cs +++ b/tests/Thinktecture.EntityFrameworkCore.PostgreSQL.Tests/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutorTests/BulkOperationOutputAsync.cs @@ -95,4 +95,62 @@ public async Task Should_throw_if_the_projection_reads_a_navigation() .Should().ThrowAsync() .WithMessage("'Parent' is not a scalar property*"); } -} \ No newline at end of file + + [Fact] + public async Task Should_return_the_concrete_types_of_a_TPH_hierarchy_with_a_concrete_base_type() + { + var shapes = TphTestData.CreateShapes(); + + var result = await ActDbContext.BulkInsertOrUpdateAsync(shapes, new NpgsqlBulkInsertOrUpdateOptions(), row => row.Inserted); + + result.Should().BeEquivalentTo(shapes.Cast(), options => options.PreferringRuntimeMemberTypes()); + result.Select(shape => shape.GetType()).Should().BeEquivalentTo(shapes.Select(shape => shape.GetType())); + } + + [Fact] + public async Task Should_return_the_stored_type_if_it_differs_from_the_type_of_the_input() + { + ArrangeDbContext.AddRange(TphTestData.CreateShapes()); + await ArrangeDbContext.SaveChangesAsync(); + + // The row is a circle. The input is a plain shape that only renames it, so the stored discriminator is kept. + var input = new Shape { Id = TphTestData.C1Id, Name = "renamed" }; + var options = new NpgsqlBulkInsertOrUpdateOptions { PropertiesToUpdate = IEntityPropertiesProvider.Include(shape => shape.Name) }; + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { input }, options, row => row.Inserted); + + var circle = result.Should().ContainSingle().Which.Should().BeOfType().Subject; + circle.Name.Should().Be("renamed"); + circle.Radius.Should().Be(3); + circle.Color.Should().Be("red"); + } + + [Fact] + public async Task Should_return_the_properties_of_an_abstract_TPH_base_type() + { + var documents = new List + { + new Invoice { Id = new Guid("5A0B1C2D-0031-4000-8000-000000000001"), Kind = 1, Title = "invoice", Total = 5 }, + new Report { Id = new Guid("5A0B1C2D-0031-4000-8000-000000000002"), Kind = 2, Title = "report", Pages = 3 } + }; + + var ids = await ActDbContext.BulkInsertOrUpdateAsync(documents, new NpgsqlBulkInsertOrUpdateOptions(), row => row.Inserted.Id); + + ids.Should().BeEquivalentTo(documents.Select(document => document.Id)); + + var whole = await ActDbContext.BulkInsertOrUpdateAsync(documents, new NpgsqlBulkInsertOrUpdateOptions(), row => row.Inserted); + + whole.Should().BeEquivalentTo(documents.Cast(), options => options.PreferringRuntimeMemberTypes()); + whole.Select(document => document.GetType()).Should().BeEquivalentTo(new[] { typeof(Invoice), typeof(Report) }); + } + + [Fact] + public async Task Should_throw_if_the_projection_reads_a_navigation_besides_the_whole_entity() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name" }; + + await ActDbContext.Awaiting(ctx => ctx.BulkInsertOrUpdateAsync(new[] { entity }, new NpgsqlBulkInsertOrUpdateOptions(), row => new { Entity = row.Inserted, row.Inserted.Parent })) + .Should().ThrowAsync() + .WithMessage("'Parent' is not a scalar property*"); + } +} diff --git a/tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutorTests/MergeOutput.cs b/tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutorTests/MergeOutput.cs index 7b721894..9737dce1 100644 --- a/tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutorTests/MergeOutput.cs +++ b/tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutorTests/MergeOutput.cs @@ -186,4 +186,84 @@ public async Task Should_throw_if_the_projection_reads_a_navigation() .Should().ThrowAsync() .WithMessage("'Parent' is not a scalar property*"); } + + [Fact] + public async Task Should_return_the_concrete_types_of_a_TPH_hierarchy_with_a_concrete_base_type() + { + var shapes = TphTestData.CreateShapes(); + + var result = await ActDbContext.BulkInsertOrUpdateAsync(shapes, new SqlServerBulkInsertOrUpdateOptions(), row => row.Inserted); + + result.Should().BeEquivalentTo(shapes.Cast(), options => options.PreferringRuntimeMemberTypes()); + result.Select(shape => shape.GetType()).Should().BeEquivalentTo(shapes.Select(shape => shape.GetType())); + } + + [Fact] + public async Task Should_return_the_stored_type_if_it_differs_from_the_type_of_the_input() + { + ArrangeDbContext.AddRange(TphTestData.CreateShapes()); + await ArrangeDbContext.SaveChangesAsync(); + + // The row is a circle. The input is a plain shape that only renames it, so the stored discriminator is kept. + var input = new Shape { Id = TphTestData.C1Id, Name = "renamed" }; + var options = new SqlServerBulkInsertOrUpdateOptions { PropertiesToUpdate = IEntityPropertiesProvider.Include(shape => shape.Name) }; + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { input }, options, row => row.Inserted); + + var circle = result.Should().ContainSingle().Which.Should().BeOfType().Subject; + circle.Name.Should().Be("renamed"); + circle.Radius.Should().Be(3); + circle.Color.Should().Be("red"); + } + + [Fact] + public async Task Should_return_the_properties_of_an_abstract_TPH_base_type() + { + var documents = new List + { + new Invoice { Id = new Guid("5A0B1C2D-0031-4000-8000-000000000001"), Kind = 1, Title = "invoice", Total = 5 }, + new Report { Id = new Guid("5A0B1C2D-0031-4000-8000-000000000002"), Kind = 2, Title = "report", Pages = 3 } + }; + + var ids = await ActDbContext.BulkInsertOrUpdateAsync(documents, new SqlServerBulkInsertOrUpdateOptions(), row => row.Inserted.Id); + + ids.Should().BeEquivalentTo(documents.Select(document => document.Id)); + + var whole = await ActDbContext.BulkInsertOrUpdateAsync(documents, new SqlServerBulkInsertOrUpdateOptions(), row => row.Inserted); + + whole.Should().BeEquivalentTo(documents.Cast(), options => options.PreferringRuntimeMemberTypes()); + whole.Select(document => document.GetType()).Should().BeEquivalentTo(new[] { typeof(Invoice), typeof(Report) }); + } + + [Fact] + public async Task Should_throw_if_the_projection_reads_a_navigation_besides_the_whole_entity() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name" }; + + await ActDbContext.Awaiting(ctx => ctx.BulkInsertOrUpdateAsync(new[] { entity }, new SqlServerBulkInsertOrUpdateOptions(), row => new { Entity = row.Inserted, row.Inserted.Parent })) + .Should().ThrowAsync() + .WithMessage("'Parent' is not a scalar property*"); + } + [Fact] + public async Task Should_reset_properties_to_null_if_the_database_returns_NULL() + { + var newEntity = new TestEntity { Id = _NEW_ID, RequiredName = "Inserted", Count = 3 }; + + // TestEntity initializes RequiredName with an empty string. The deleted columns of an inserted row are NULL. + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { newEntity }, + new SqlServerBulkInsertOrUpdateOptions(), + row => new { OldRequiredName = row.Deleted.RequiredName, OldCount = row.Deleted.Count }); + + result.Should().ContainSingle().Which.Should().Be(new { OldRequiredName = (string?)null, OldCount = 0 }); + } + + [Fact] + public async Task Should_throw_if_the_projection_reads_a_navigation_of_the_deleted_row_besides_the_whole_entity() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name" }; + + await ActDbContext.Awaiting(ctx => ctx.BulkInsertOrUpdateAsync(new[] { entity }, new SqlServerBulkInsertOrUpdateOptions(), row => new { Entity = row.Deleted, row.Deleted.Parent })) + .Should().ThrowAsync() + .WithMessage("'Parent' is not a scalar property*"); + } } diff --git a/tests/Thinktecture.EntityFrameworkCore.Sqlite.Tests/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutorTests/BulkOperationOutputAsync.cs b/tests/Thinktecture.EntityFrameworkCore.Sqlite.Tests/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutorTests/BulkOperationOutputAsync.cs index 170a0659..72c81e53 100644 --- a/tests/Thinktecture.EntityFrameworkCore.Sqlite.Tests/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutorTests/BulkOperationOutputAsync.cs +++ b/tests/Thinktecture.EntityFrameworkCore.Sqlite.Tests/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutorTests/BulkOperationOutputAsync.cs @@ -92,4 +92,62 @@ public async Task Should_throw_if_the_projection_reads_a_navigation() .Should().ThrowAsync() .WithMessage("'Parent' is not a scalar property*"); } -} \ No newline at end of file + + [Fact] + public async Task Should_return_the_concrete_types_of_a_TPH_hierarchy_with_a_concrete_base_type() + { + var shapes = TphTestData.CreateShapes(); + + var result = await ActDbContext.BulkInsertOrUpdateAsync(shapes, new SqliteBulkInsertOrUpdateOptions(), row => row.Inserted); + + result.Should().BeEquivalentTo(shapes.Cast(), options => options.PreferringRuntimeMemberTypes()); + result.Select(shape => shape.GetType()).Should().BeEquivalentTo(shapes.Select(shape => shape.GetType())); + } + + [Fact] + public async Task Should_return_the_stored_type_if_it_differs_from_the_type_of_the_input() + { + ArrangeDbContext.AddRange(TphTestData.CreateShapes()); + await ArrangeDbContext.SaveChangesAsync(); + + // The row is a circle. The input is a plain shape that only renames it, so the stored discriminator is kept. + var input = new Shape { Id = TphTestData.C1Id, Name = "renamed" }; + var options = new SqliteBulkInsertOrUpdateOptions { PropertiesToUpdate = IEntityPropertiesProvider.Include(shape => shape.Name) }; + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { input }, options, row => row.Inserted); + + var circle = result.Should().ContainSingle().Which.Should().BeOfType().Subject; + circle.Name.Should().Be("renamed"); + circle.Radius.Should().Be(3); + circle.Color.Should().Be("red"); + } + + [Fact] + public async Task Should_return_the_properties_of_an_abstract_TPH_base_type() + { + var documents = new List + { + new Invoice { Id = new Guid("5A0B1C2D-0031-4000-8000-000000000001"), Kind = 1, Title = "invoice", Total = 5 }, + new Report { Id = new Guid("5A0B1C2D-0031-4000-8000-000000000002"), Kind = 2, Title = "report", Pages = 3 } + }; + + var ids = await ActDbContext.BulkInsertOrUpdateAsync(documents, new SqliteBulkInsertOrUpdateOptions(), row => row.Inserted.Id); + + ids.Should().BeEquivalentTo(documents.Select(document => document.Id)); + + var whole = await ActDbContext.BulkInsertOrUpdateAsync(documents, new SqliteBulkInsertOrUpdateOptions(), row => row.Inserted); + + whole.Should().BeEquivalentTo(documents.Cast(), options => options.PreferringRuntimeMemberTypes()); + whole.Select(document => document.GetType()).Should().BeEquivalentTo(new[] { typeof(Invoice), typeof(Report) }); + } + + [Fact] + public async Task Should_throw_if_the_projection_reads_a_navigation_besides_the_whole_entity() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name" }; + + await ActDbContext.Awaiting(ctx => ctx.BulkInsertOrUpdateAsync(new[] { entity }, new SqliteBulkInsertOrUpdateOptions(), row => new { Entity = row.Inserted, row.Inserted.Parent })) + .Should().ThrowAsync() + .WithMessage("'Parent' is not a scalar property*"); + } +} From bd96c5f2787c70790f3df1e36d088c0d4fff8822 Mon Sep 17 00:00:00 2001 From: pengweiqhca Date: Thu, 3 Dec 2026 20:43:14 +0800 Subject: [PATCH 6/7] Reject whole-entity projections with complex or owned members and read 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. --- .../Internal/BulkOperationOutputMapper.cs | 25 +++++++- .../BulkOperationOutputMapperTests.cs | 57 +++++++++++++++++++ ...yFrameworkCore.BulkOperations.Tests.csproj | 1 + ...ulkOperationOutputMapperScalarTypeTests.cs | 48 ++++++++++++++++ ...ulkOperationOutputMapperScalarTypeTests.cs | 48 ++++++++++++++++ 5 files changed, 178 insertions(+), 1 deletion(-) create mode 100644 tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperTests.cs create mode 100644 tests/Thinktecture.EntityFrameworkCore.PostgreSQL.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperScalarTypeTests.cs create mode 100644 tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperScalarTypeTests.cs diff --git a/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationOutputMapper.cs b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationOutputMapper.cs index 90a46982..c3c6cd28 100644 --- a/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationOutputMapper.cs +++ b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationOutputMapper.cs @@ -72,6 +72,9 @@ public static BulkOperationOutputMapper Create( : throw new NotSupportedException($"'{name}' is not a scalar property of the entity '{entityType.DisplayName()}' that is mapped to a column of table '{storeObject.Name}'. Only such properties can be selected from the returned row.")) .ToList(); + if (all) + EnsureNoUnsupportedMembers(entityType, storeObject); + var properties = all ? GetAllProperties(entityType, storeObject) : members; @@ -156,6 +159,20 @@ private ConcreteType GetConcreteType(DbDataReader reader, int firstOrdinal) : throw new InvalidOperationException($"The discriminator value '{value}' returned by the database does not belong to an entity type of the hierarchy of '{typeof(T).Name}'."); } + // The whole entity has the scalar properties only. Complex properties and owned types that are stored in the table would be missing + // in the returned entity, so the projection must select their scalar properties explicitly. + private static void EnsureNoUnsupportedMembers(IEntityType entityType, StoreObjectIdentifier storeObject) + { + foreach (var type in entityType.GetDerivedTypesInclusive()) + { + if (type.GetDeclaredComplexProperties().FirstOrDefault() is { } complexProperty) + throw new NotSupportedException($"The entity '{entityType.DisplayName()}' has the complex property '{complexProperty.Name}', which cannot be returned as part of the whole entity. Select the scalar properties that are needed instead."); + + if (type.GetDeclaredNavigations().FirstOrDefault(navigation => navigation.ForeignKey.IsOwnership && navigation.TargetEntityType.GetTableName() == storeObject.Name) is { } ownedType) + throw new NotSupportedException($"The entity '{entityType.DisplayName()}' has the owned type '{ownedType.Name}' that is stored in the same table, which cannot be returned as part of the whole entity. Select the scalar properties that are needed instead."); + } + } + private static List GetAllProperties(IEntityType entityType, StoreObjectIdentifier storeObject) { return entityType.GetProperties() @@ -258,7 +275,13 @@ public void Apply(object entity, DbDataReader reader, int ordinal) { var reader = Expression.Parameter(typeof(DbDataReader)); var ordinal = Expression.Parameter(typeof(int)); - var call = Expression.Call(reader, typeMapping.GetDataReaderMethod(), ordinal); + var method = typeMapping.GetDataReaderMethod(); + + // Some methods are declared on the reader of the provider, e.g. SqlDataReader.GetDateTimeOffset. + Expression instance = method.DeclaringType!.IsAssignableFrom(typeof(DbDataReader)) + ? reader + : Expression.Convert(reader, method.DeclaringType); + var call = Expression.Call(instance, method, ordinal); return Expression.Lambda>(Expression.Convert(call, typeof(object)), reader, ordinal).Compile(); } diff --git a/tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperTests.cs b/tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperTests.cs new file mode 100644 index 00000000..74bd4bf4 --- /dev/null +++ b/tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperTests.cs @@ -0,0 +1,57 @@ +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage; +using Thinktecture.EntityFrameworkCore.BulkOperations.Internal; +using Thinktecture.TestDatabaseContext; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +public class BulkOperationOutputMapperTests +{ + [Fact] + public void Should_reject_the_whole_entity_if_it_has_a_complex_property() + { + var (entityType, storeObject) = GetEntityType(TestEntityWithComplexType.Configure); + + var act = () => BulkOperationOutputMapper.Create(entityType, storeObject, true, []); + + act.Should().Throw().WithMessage("*complex property 'Boundary'*"); + } + + [Fact] + public void Should_allow_scalar_properties_of_an_entity_with_a_complex_property() + { + var (entityType, storeObject) = GetEntityType(TestEntityWithComplexType.Configure); + + var mapper = BulkOperationOutputMapper.Create(entityType, storeObject, false, [nameof(TestEntityWithComplexType.Id)]); + + mapper.Columns.Select(column => column.ColumnName).Should().Equal("Id"); + } + + [Fact] + public void Should_reject_the_whole_entity_if_it_has_an_owned_type_in_the_same_table() + { + var options = new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options; + using var context = new TestDbContext(options); + var entityType = context.Model.GetEntityType(typeof(Vehicle)); + var storeObject = StoreObjectIdentifier.Create(entityType, StoreObjectType.Table)!.Value; + + var act = () => BulkOperationOutputMapper.Create(entityType, storeObject, true, []); + + act.Should().Throw().WithMessage("*owned type 'Inline'*"); + } + + private static (IEntityType EntityType, StoreObjectIdentifier StoreObject) GetEntityType(Action configure) + { + var options = new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options; + using var context = new MapperDbContext(options, configure); + + var entityType = context.Model.FindEntityType(typeof(T))!; + + return (entityType, StoreObjectIdentifier.Create(entityType, StoreObjectType.Table)!.Value); + } + + private sealed class MapperDbContext(DbContextOptions options, Action configure) : DbContext(options) + { + protected override void OnModelCreating(ModelBuilder modelBuilder) => configure(modelBuilder); + } +} \ No newline at end of file diff --git a/tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests.csproj b/tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests.csproj index 8ab3273a..ded3c38a 100644 --- a/tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests.csproj +++ b/tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests.csproj @@ -10,6 +10,7 @@ + diff --git a/tests/Thinktecture.EntityFrameworkCore.PostgreSQL.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperScalarTypeTests.cs b/tests/Thinktecture.EntityFrameworkCore.PostgreSQL.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperScalarTypeTests.cs new file mode 100644 index 00000000..2268d5a2 --- /dev/null +++ b/tests/Thinktecture.EntityFrameworkCore.PostgreSQL.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperScalarTypeTests.cs @@ -0,0 +1,48 @@ +using Microsoft.EntityFrameworkCore.Metadata; +using Thinktecture.EntityFrameworkCore.BulkOperations.Internal; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +// No database is needed: the failure happened while the mapper was created. +public class BulkOperationOutputMapperScalarTypeTests +{ + [Fact] + public void Should_create_the_mapper_for_all_scalar_types_of_the_provider() + { + var options = new DbContextOptionsBuilder().UseNpgsql("Host=localhost;Database=NotUsed").Options; + using var context = new ScalarDbContext(options); + + var entityType = context.Model.FindEntityType(typeof(ScalarEntity))!; + var storeObject = StoreObjectIdentifier.Create(entityType, StoreObjectType.Table)!.Value; + + var mapper = BulkOperationOutputMapper.Create(entityType, storeObject, true, []); + + mapper.Columns.Should().HaveCount(entityType.GetProperties().Count()); + } + + private sealed class ScalarEntity + { + public Guid Id { get; set; } + public DateTimeOffset At { get; set; } + public TimeSpan Span { get; set; } + public DateTime Moment { get; set; } + public DateOnly Day { get; set; } + public TimeOnly Time { get; set; } + public decimal Amount { get; set; } + public double Ratio { get; set; } + public float Small { get; set; } + public bool Flag { get; set; } + public short Short { get; set; } + public long Big { get; set; } + public char Letter { get; set; } + public byte[] Bytes { get; set; } = []; + public string Text { get; set; } = string.Empty; + public int[] Numbers { get; set; } = []; + public List Names { get; set; } = []; + } + + private sealed class ScalarDbContext(DbContextOptions options) : DbContext(options) + { + protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().ToTable("Scalar"); + } +} \ No newline at end of file diff --git a/tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperScalarTypeTests.cs b/tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperScalarTypeTests.cs new file mode 100644 index 00000000..8971c286 --- /dev/null +++ b/tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperScalarTypeTests.cs @@ -0,0 +1,48 @@ +using Microsoft.EntityFrameworkCore.Metadata; +using Thinktecture.EntityFrameworkCore.BulkOperations.Internal; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +// No database is needed: the failure happened while the mapper was created. +public class BulkOperationOutputMapperScalarTypeTests +{ + [Fact] + public void Should_create_the_mapper_for_all_scalar_types_of_the_provider() + { + var options = new DbContextOptionsBuilder().UseSqlServer("Server=.;Database=NotUsed").Options; + using var context = new TemporalDbContext(options); + + var entityType = context.Model.FindEntityType(typeof(TemporalEntity))!; + var storeObject = StoreObjectIdentifier.Create(entityType, StoreObjectType.Table)!.Value; + + // SqlServerDateTimeOffsetTypeMapping and SqlServerTimeOnlyTypeMapping use methods of SqlDataReader. + var mapper = BulkOperationOutputMapper.Create(entityType, storeObject, true, []); + + mapper.Columns.Select(column => column.ColumnName).Should().HaveCount(16); + } + + private sealed class TemporalEntity + { + public Guid Id { get; set; } + public DateTimeOffset At { get; set; } + public TimeSpan Span { get; set; } + public DateTime Moment { get; set; } + public DateOnly Day { get; set; } + public TimeOnly Time { get; set; } + public decimal Amount { get; set; } + public double Ratio { get; set; } + public float Small { get; set; } + public bool Flag { get; set; } + public byte Tiny { get; set; } + public short Short { get; set; } + public long Big { get; set; } + public char Letter { get; set; } + public byte[] Bytes { get; set; } = []; + public string Text { get; set; } = string.Empty; + } + + private sealed class TemporalDbContext(DbContextOptions options) : DbContext(options) + { + protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().ToTable("Temporal"); + } +} \ No newline at end of file From ec6cbcea93ce1e5fd91373b4e5026a4f74bc0580 Mon Sep 17 00:00:00 2001 From: pengweiqhca Date: Thu, 3 Dec 2026 21:21:07 +0800 Subject: [PATCH 7/7] Reject inherited complex properties and owned types in whole-entity projections 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. --- .../Internal/BulkOperationOutputMapper.cs | 20 ++++++++++++------- .../BulkOperationOutputMapperTests.cs | 14 +++++++++++++ 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationOutputMapper.cs b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationOutputMapper.cs index c3c6cd28..23d3c7e5 100644 --- a/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationOutputMapper.cs +++ b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationOutputMapper.cs @@ -163,14 +163,20 @@ private ConcreteType GetConcreteType(DbDataReader reader, int firstOrdinal) // in the returned entity, so the projection must select their scalar properties explicitly. private static void EnsureNoUnsupportedMembers(IEntityType entityType, StoreObjectIdentifier storeObject) { - foreach (var type in entityType.GetDerivedTypesInclusive()) - { - if (type.GetDeclaredComplexProperties().FirstOrDefault() is { } complexProperty) - throw new NotSupportedException($"The entity '{entityType.DisplayName()}' has the complex property '{complexProperty.Name}', which cannot be returned as part of the whole entity. Select the scalar properties that are needed instead."); + // The members of the base types are inherited, the members of the derived types are declared on them. + var complexProperty = entityType.GetComplexProperties() + .Concat(entityType.GetDerivedTypes().SelectMany(static type => type.GetDeclaredComplexProperties())) + .FirstOrDefault(); - if (type.GetDeclaredNavigations().FirstOrDefault(navigation => navigation.ForeignKey.IsOwnership && navigation.TargetEntityType.GetTableName() == storeObject.Name) is { } ownedType) - throw new NotSupportedException($"The entity '{entityType.DisplayName()}' has the owned type '{ownedType.Name}' that is stored in the same table, which cannot be returned as part of the whole entity. Select the scalar properties that are needed instead."); - } + if (complexProperty is not null) + throw new NotSupportedException($"The entity '{entityType.DisplayName()}' has the complex property '{complexProperty.Name}', which cannot be returned as part of the whole entity. Select the scalar properties that are needed instead."); + + var ownedType = entityType.GetNavigations() + .Concat(entityType.GetDerivedTypes().SelectMany(static type => type.GetDeclaredNavigations())) + .FirstOrDefault(navigation => navigation.ForeignKey.IsOwnership && navigation.TargetEntityType.GetTableName() == storeObject.Name); + + if (ownedType is not null) + throw new NotSupportedException($"The entity '{entityType.DisplayName()}' has the owned type '{ownedType.Name}' that is stored in the same table, which cannot be returned as part of the whole entity. Select the scalar properties that are needed instead."); } private static List GetAllProperties(IEntityType entityType, StoreObjectIdentifier storeObject) diff --git a/tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperTests.cs b/tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperTests.cs index 74bd4bf4..8808a0d4 100644 --- a/tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperTests.cs +++ b/tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperTests.cs @@ -40,6 +40,20 @@ public void Should_reject_the_whole_entity_if_it_has_an_owned_type_in_the_same_t act.Should().Throw().WithMessage("*owned type 'Inline'*"); } + [Fact] + public void Should_reject_the_whole_entity_if_an_owned_type_in_the_same_table_is_inherited() + { + var options = new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options; + using var context = new TestDbContext(options); + var entityType = context.Model.GetEntityType(typeof(Car)); + var storeObject = StoreObjectIdentifier.Create(entityType, StoreObjectType.Table)!.Value; + + // Vehicle owns Inline, Car inherits it. + var act = () => BulkOperationOutputMapper.Create(entityType, storeObject, true, []); + + act.Should().Throw().WithMessage("*owned type 'Inline'*"); + } + private static (IEntityType EntityType, StoreObjectIdentifier StoreObject) GetEntityType(Action configure) { var options = new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options;