Skip to content

Interceptor support for bulk updates #30869

Open

Description

@gediminas-eldorado

In our app, we have some rules, which we want applied always, when a save to database happens.

For example: set modified date.

Previously, this could easily be achieved with interceptors.

Now, with bulk updates, it seems that this logic needs to be included manually to each bulk update command.

Question: Is there a way to intercept bulk update operations currently? If not, is there a possibility for this in the future?

Thanks.

Activity

  1. added this to the Backlog milestone on May 10, 2023
  2. roji commented on May 11, 2023

    @roji
    Member

    This is something that should be possible via the new LINQ expression tree interceptor, though it's probably not trivial to do.

  3. gediminas-eldorado commented on May 11, 2023

    @gediminas-eldorado
    Author

    We were also thinking that this could be achieved via computed columns, but a solution not resorting to raw sql queries does seem cleaner.

  4. rjperes commented on Jun 28, 2024

    @rjperes

    I implemented something similar for bulk deletes, to implement soft-delete functionality. Might be useful to others, this requirement (e.g., set audit fields) would be very easy to implement, actually: https://weblogs.asp.net/ricardoperes/soft-deletes-with-entity-framework-core-bulk-deletes

  5. added theissue type on Jun 15, 2025
  6. Dreamescaper commented on Oct 9, 2026

    @Dreamescaper

    This is something that should be possible via the new LINQ expression tree interceptor

    Confirming that this works for timestamps. Below is a working implementation on EF Core 10 + Npgsql 10, along with a caveat for per-user audit fields such as ModifiedBy, where this approach does not work.

    Auto-stamping Modified on ExecuteUpdate

    In EF Core 10, ExecuteUpdate reaches IQueryExpressionInterceptor.QueryCompilationStarting as a call to EntityFrameworkQueryableExtensions.ExecuteUpdate<T>(IQueryable<T>, IReadOnlyList<ITuple>). The setters are a NewArrayExpression of new Tuple<Delegate, object>(propertySelector, valueOrValueSelector). You can append one more setter:

    public interface ITimestampedEntity
    {
        DateTime Modified { get; set; }
    }
    
    public class TimestampedEntityInterceptor : IQueryExpressionInterceptor
    {
        private static readonly ConstructorInfo SetterConstructor =
            typeof(Tuple<Delegate, object>).GetConstructor([typeof(Delegate), typeof(object)])!;
    
        private static readonly PropertyInfo UtcNowProperty = typeof(DateTime).GetProperty(nameof(DateTime.UtcNow))!;
    
        public Expression QueryCompilationStarting(Expression queryExpression, QueryExpressionEventData eventData)
        {
            if (queryExpression is not MethodCallExpression
                {
                    Method: { Name: nameof(EntityFrameworkQueryableExtensions.ExecuteUpdate), IsGenericMethod: true } method,
                    Arguments: [var source, NewArrayExpression setters]
                } call
                || method.DeclaringType != typeof(EntityFrameworkQueryableExtensions))
            {
                return queryExpression;
            }
    
            var entityType = method.GetGenericArguments()[0];
            if (!typeof(ITimestampedEntity).IsAssignableFrom(entityType) || SetsModified(setters))
            {
                return queryExpression;
            }
    
            // The compiled query is cached, so the value must not be a constant captured now.
            // DateTime.UtcNow inside a value selector is translated to SQL (now() on Npgsql).
            var entity = Expression.Parameter(entityType, "e");
            var modifiedSetter = Expression.New(
                SetterConstructor,
                Expression.Lambda(Expression.Property(entity, nameof(ITimestampedEntity.Modified)), entity),
                Expression.Lambda(Expression.Property(null, UtcNowProperty), entity));
    
            return call.Update(call.Object, [source, setters.Update([.. setters.Expressions, modifiedSetter])]);
        }
    
        // An explicit Modified setter wins; a duplicate setter would make EF reject the update.
        private static bool SetsModified(NewArrayExpression setters) =>
            setters.Expressions.Any(setter => setter is NewExpression
            {
                Arguments: [LambdaExpression { Body: MemberExpression { Member.Name: nameof(ITimestampedEntity.Modified) } }, _]
            });
    }

    I tested this against a real PostgreSQL database. It works for sync and async calls, stamps each execution of a cached query separately, keeps an explicit Modified setter, and leaves other entity types alone. Note that the timestamp comes from the database clock, not the application clock. The setter shape is internal and may change in a future EF version.

    Why this does not work for per-user values (ModifiedBy)

    The interceptor runs at the wrong point in the query pipeline:

    1. EF extracts parameters. Closure values such as a captured email are evaluated and replaced by parameter placeholders.
    2. EF builds the compiled-query cache key from that rewritten tree, then looks it up.
    3. Only on a cache miss does EF compile the query. QueryCompilationStarting runs here, inside CompiledQueryCache.GetOrAddQuery.

    This causes the following problems:

    • A captured value is rejected. Step 1 has already run, so nothing turns the captured value into a parameter. Translation fails with The following lambda argument to 'SetProperty' does not represent a valid value: 'p => Holder.Value'.
    • A constant sticks. If the interceptor adds Expression.Constant(currentUser), the constant is compiled into the cached query. The cache key was built before the rewrite, so it doesn't include the user. On a cache hit the interceptor isn't called at all, so the next user's update writes the first user's name.
    • A new parameter has no value. Parameter values for each execution are collected in step 1, so a placeholder added in step 3 never gets one.

    Modified works only because DateTime.UtcNow has a SQL translation that the database evaluates on each run.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions