I have the following entity:
public class User
{
public int UserId { get; set; }
public string UserName { get; set; }
public string UserAddress { get; set; }
public DateTime CreateDate { get; set; }
public DateTime? UpdateDate { get; set; }
}
How can I make the UpdateDate
field of the User
entity become the server DateTime
on an update? That is to say, whenever an entity in the database becomes modified, the UpdateDate
field changes to that exact date and time as well as if to say UpdateDate = new DateTime(Datetime.Now.Ticks)
You can do this only with migrations. Set defaultSqlValue parameter for UpdateDate property to "GETDATE()" or "GETUTCDATE()" and when you modify or add new entity you would need to set its value to null.
First, consider that
DateTimeOffset
is a better choice if you are going to be storing local times. Alternatively, you could use a UTC-basedDateTime
, but I will showDateTimeOffset
in this example. Never store a local-basedDateTime
for this purpose, as you will have issues with time zones and daylight saving time. See also: The Case Against DateTime.Now.Next, consider a common interface that you can use for entities that you wish to track created/updated values.
Apply that interface and its properties to the entities you are working with.
Now in your database context, you can attach to the
SavingChanges
event and apply the desired behavior:Note the final call to
DetectChanges
, which will ensure that the new updated date values are applied to all modified entities.