You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
publicinterfaceITimestampedEntity{DateTimeModified{get;set;}}publicclassTimestampedEntityInterceptor:IQueryExpressionInterceptor{privatestaticreadonlyConstructorInfoSetterConstructor=typeof(Tuple<Delegate,object>).GetConstructor([typeof(Delegate),typeof(object)])!;privatestaticreadonlyPropertyInfoUtcNowProperty=typeof(DateTime).GetProperty(nameof(DateTime.UtcNow))!;publicExpressionQueryCompilationStarting(ExpressionqueryExpression,QueryExpressionEventDataeventData){if(queryExpressionis not MethodCallExpression{Method:{Name:nameof(EntityFrameworkQueryableExtensions.ExecuteUpdate),IsGenericMethod:true}method,Arguments:[varsource,NewArrayExpressionsetters]}call||method.DeclaringType!=typeof(EntityFrameworkQueryableExtensions)){returnqueryExpression;}varentityType=method.GetGenericArguments()[0];if(!typeof(ITimestampedEntity).IsAssignableFrom(entityType)||SetsModified(setters)){returnqueryExpression;}// 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).varentity=Expression.Parameter(entityType,"e");varmodifiedSetter=Expression.New(SetterConstructor,Expression.Lambda(Expression.Property(entity,nameof(ITimestampedEntity.Modified)),entity),Expression.Lambda(Expression.Property(null,UtcNowProperty),entity));returncall.Update(call.Object,[source,setters.Update([..setters.Expressions,modifiedSetter])]);}// An explicit Modified setter wins; a duplicate setter would make EF reject the update.privatestaticboolSetsModified(NewArrayExpressionsetters)=>setters.Expressions.Any(setter =>setterisNewExpression{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:
EF extracts parameters. Closure values such as a captured email are evaluated and replaced by parameter placeholders.
EF builds the compiled-query cache key from that rewritten tree, then looks it up.
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.
Activity
roji commentedon May 11, 2023
This is something that should be possible via the new LINQ expression tree interceptor, though it's probably not trivial to do.
gediminas-eldorado commentedon May 11, 2023
We were also thinking that this could be achieved via computed columns, but a solution not resorting to raw sql queries does seem cleaner.
rjperes commentedon Jun 28, 2024
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
Dreamescaper commentedon Oct 9, 2026
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
ModifiedonExecuteUpdateIn EF Core 10,
ExecuteUpdatereachesIQueryExpressionInterceptor.QueryCompilationStartingas a call toEntityFrameworkQueryableExtensions.ExecuteUpdate<T>(IQueryable<T>, IReadOnlyList<ITuple>). The setters are aNewArrayExpressionofnew Tuple<Delegate, object>(propertySelector, valueOrValueSelector). You can append one more setter: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
Modifiedsetter, 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:
emailare evaluated and replaced by parameter placeholders.QueryCompilationStartingruns here, insideCompiledQueryCache.GetOrAddQuery.This causes the following problems:
The following lambda argument to 'SetProperty' does not represent a valid value: 'p => Holder.Value'.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.Modifiedworks only becauseDateTime.UtcNowhas a SQL translation that the database evaluates on each run.