I am creating models using Entity Framework 6.1.3 and I would like to store the UTC date and time of when a row is created and when it was last updated.
I have the following model (simplified):
namespace Sapphire.Cms.Models {
using System;
using System.ComponentModel.DataAnnotations;
public class SiteTree {
[Required]
[DataType(DataType.DateTime)]
[Display(Name = "Created")]
public DateTime Created { get; set; }
[Required]
[DataType(DataType.DateTime)]
[Display(Name = "Last Updated")]
public DateTime LastUpdated { get; set; }
}
}
For the Created field, I would like to store the UTC date and time of when the row was created in a datetime field named Created in MSSQL.
For the LastUpdated field, I would like to store the UTC date and time of when the row was last updated in a datetime field named LastUpdated in MSSQL every time the row is updated.
I would like the ability to use attributes so that I can indicate when this data should automatically be populated.
For instance, for the LastUpdated property:
[Required]
[DataType(DataType.DateTime)]
[Display(Name = "Last Updated")]
[TrackLastUpdated]
public DateTime LastUpdated { get; set; }
I want the ability to use these attributes for other models too.
The timezone on the server changes from GMT to BST and back, so storing this value in UTC and getting the value out in UTC is vitally important.
There are similar questions on SO, but none using attributes from what I can see:
- Entity Framework Code First Date field creation
- Tell EF to automatically compute and insert the current date time when the row is created?
I'm hoping that EF already has some attributes to do this however I can't seem to find them. If not can someone please explain how I can achieve this?