I have CreatedAt and UpdatedAt columns in my User model.
User.cs
public string Name { get; set; }
public DateTime? CreatedAt { get; set; }
public DateTime? UpdatedAt { get; set; }
Requirement
- When we
SaveChanges()user records,CreatedAtandUpdatedAtshould automatically saved e.g:DateTime.UtcNow - When I update
Userrecord, onlyUpdatedAtcolumn should get updated to current date time. - And this should happen automatically for all other models, may be some configuration in
OnModelCreating(). - I want this behavior to find
latestrecords from the database, and other places too. - I am using
code firstmigration approach - I am using MySQL server,
MySql.Data,MySql.Data.Entity.EF6.
UPDATE
I added BaseEntity.cs model
public abstract class BaseEntity
{
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
Inheriting User from BaseEntity
public class User : BaseEntity
{
public int Id { get; set; }
public int FullName { get; set; }
}
and updated migrations to include defaultValueSql()
AddColumn("dbo.Users", "CreatedAt", c => c.DateTime(nullable: false, precision: 0, defaultValueSql: "NOW()"));
AddColumn("dbo.Users", "UpdatedAt", c => c.DateTime(nullable: false, precision: 0, defaultValueSql: "NOW()"));"
Now, need a way to fix UpdatedAt column in each update.