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/BulkOperationOutputMapper.cs b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationOutputMapper.cs
new file mode 100644
index 00000000..23d3c7e5
--- /dev/null
+++ b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationOutputMapper.cs
@@ -0,0 +1,295 @@
+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();
+
+ if (all)
+ EnsureNoUnsupportedMembers(entityType, storeObject);
+
+ 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}'.");
+ }
+
+ // 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)
+ {
+ // 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 (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)
+ {
+ 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 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/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..a5fe5ee2
--- /dev/null
+++ b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationReturningProjection.cs
@@ -0,0 +1,132 @@
+using System.Data.Common;
+using System.Linq.Expressions;
+using Microsoft.EntityFrameworkCore.Metadata;
+using Microsoft.EntityFrameworkCore.Storage;
+
+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 BulkOperationOutputMapper _mapper;
+ private readonly Func, TResult> _projection;
+
+ ///
+ /// The names of the columns to return, in the order in which reads them.
+ ///
+ public IReadOnlyList ColumnNames { get; }
+
+ private BulkOperationReturningProjection(BulkOperationOutputMapper mapper, Func, TResult> projection)
+ {
+ _mapper = mapper;
+ _projection = projection;
+ ColumnNames = mapper.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 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 (members.Count == 0 && !collector.All)
+ members = [(entityType.FindPrimaryKey()?.Properties[0] ?? entityType.GetProperties().First(property => property.GetColumnName(storeObject) is not null)).Name];
+
+ return new BulkOperationReturningProjection(BulkOperationOutputMapper.Create(entityType, storeObject, collector.All, members), output.Compile());
+ }
+
+ ///
+ /// 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);
+
+ return _projection(new BulkOperationOutput { Inserted = _mapper.Read(reader, 0) });
+ }
+
+ ///
+ /// 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;
+ }
+
+ // 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.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.
///
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.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.MergeOutput.cs b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.MergeOutput.cs
new file mode 100644
index 00000000..9fecb964
--- /dev/null
+++ b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.MergeOutput.cs
@@ -0,0 +1,132 @@
+using System.Linq.Expressions;
+using Thinktecture.EntityFrameworkCore.BulkOperations.Internal;
+using Thinktecture.Internal;
+
+namespace Thinktecture.EntityFrameworkCore.BulkOperations;
+
+public sealed partial class SqlServerBulkOperationExecutor : IBulkOperationOutputExecutor
+{
+ ///
+ /// 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);
+ }
+
+ ///
+ 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,
+ 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..ceabc0a4
--- /dev/null
+++ b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeOutputPlan.cs
@@ -0,0 +1,219 @@
+using System.Data.Common;
+using System.Linq.Expressions;
+using System.Text;
+using Microsoft.EntityFrameworkCore.Metadata;
+using Microsoft.EntityFrameworkCore.Storage;
+using Thinktecture.EntityFrameworkCore.BulkOperations.Internal;
+
+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.
+/// The columns of the table variable are the action, the columns of inserted and the columns of deleted , in this order.
+///
+internal sealed class SqlServerMergeOutputPlan
+ where T : class
+{
+ private const string _TABLE_VARIABLE = "@MergeOutput";
+ private const string _ACTION_COLUMN = "Action";
+
+ private readonly BulkOperationOutputMapper? _inserted;
+ private readonly BulkOperationOutputMapper? _deleted;
+ private readonly int _deletedOrdinal;
+ private readonly Func, TResult> _projection;
+
+ public SqlServerMergeOutputSql Sql { get; }
+
+ private SqlServerMergeOutputPlan(
+ BulkOperationOutputMapper? inserted,
+ BulkOperationOutputMapper? deleted,
+ Func, TResult> projection,
+ SqlServerMergeOutputSql sql)
+ {
+ _inserted = inserted;
+ _deleted = deleted;
+ // The first column is the action.
+ _deletedOrdinal = 1 + (inserted?.Columns.Count ?? 0);
+ _projection = projection;
+ 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 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(inserted, deleted, output.Compile(), CreateSql(sqlGenerationHelper, inserted, deleted));
+ }
+
+ 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 (_inserted is not null)
+ row.Inserted = _inserted.Read(reader, 1);
+
+ if (_deleted is not null)
+ row.Deleted = _deleted.Read(reader, _deletedOrdinal);
+
+ 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 SqlServerMergeOutputSql CreateSql(
+ ISqlGenerationHelper sqlGenerationHelper,
+ BulkOperationOutputMapper? inserted,
+ BulkOperationOutputMapper? deleted)
+ {
+ 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);
+ var ordinal = 1;
+
+ foreach (var (mapper, prefix, alias) in new[] { (inserted, "inserted.", 'i'), (deleted, "deleted.", 'd') })
+ {
+ if (mapper is null)
+ continue;
+
+ 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(
+ declaration.Append(");").ToString(),
+ output.Append(" INTO ").Append(_TABLE_VARIABLE).Append(" (").Append(into).Append(')').ToString(),
+ select.Append(" FROM ").Append(_TABLE_VARIABLE).Append(';').ToString());
+ }
+
+ // 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;
+ }
+
+ // 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; }
+ public bool UsesInserted { get; private set; }
+ public bool UsesDeleted { 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);
+ Use(isInserted);
+ return node;
+ }
+
+ // output.Inserted: the whole entity
+ if (IsSide(node, out isInserted))
+ {
+ if (isInserted)
+ AllInserted = true;
+ else
+ AllDeleted = true;
+
+ Use(isInserted);
+ 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;
+ 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;
+
+ 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/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/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/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