Efcore: Property defining expressions for update

Created on 3 Feb 2018  路  4Comments  路  Source: dotnet/efcore

A common request is to have a server-side auto-generated timestamp for any update. One way this could be implemented is through an expression defined on the property to run when that property is saved to the database. Something like:
```C#
.Property(e => e.UpdatedOn).HasUpdateSql("GetDate()");

or even
```C#
.Property(e => e.UpdatedOn).HasUpdateExpression(e => DateTime.Now);

which will then be translated.

Note that this is very similar to server-side value conversions--see #10861--except that it may not be a "conversion".

(Doors to manual and cross-check with #10768)

type-enhancement

Most helpful comment

@ajcvickers Believe me! This is one of the most wanted feature for me in EF Core 5.0. I think this should not take so much time to implement but this would be a very very useful feature and frequently used feature in EF Core.

Please implement this is in EF Core 5.0.

All 4 comments

This would be super useful and not only for update dates but for a million things. E.g. LastUpdatedBy.

@ajcvickers Believe me! This is one of the most wanted feature for me in EF Core 5.0. I think this should not take so much time to implement but this would be a very very useful feature and frequently used feature in EF Core.

Please implement this is in EF Core 5.0.

but you can basically implement this by overriding saveChanges and casting your entities to a share base or asking if it has the property and then setting it before change,

for example

internal static void AddTimestamps(BaseEntity entity, CurrentUser currentUser)
        {
            if (entity == null)
                return;

            if (entity.Id == 0)
            {
                entity.UserCreatedId = currentUser.UserId;
                entity.UserCreated = currentUser.UserName;
                entity.DateCreated = DateTime.UtcNow;
            }
            else
            {
                entity.UserModifiedId = currentUser.UserId;
                entity.UserModified = currentUser.UserName;
                entity.DateModified = DateTime.UtcNow;
            }
        }

just saying there are better things to focus energy on in my opinion

@ajcvickers This can be a very good candidate for EF Core 6.0.

Was this page helpful?
0 / 5 - 0 ratings