I want to insert current Datetime when ever a new row is inserted.
I am using Code First Approach of EF 6,MVC 5
After searching I got this
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime? CreatedDate { get; set; }
It has to be written in Models Class,but when ever a new record is inserted NULL is saved in DB,I have noticed that this is just declaration of CreatedDate,where to write CreatedDate = DateTime.Now
OR any other way to solve it.
My Entire Model
namespace December.Models
{
[Table("tblLibray")]
public class Library
{
[Key]
public int Id { get; set; }
[Required]
public string BookName { get; set; }
[Required]
public string Author { get; set; }
[Required]
public string Description { get; set; }
[Required]
public decimal MRP { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime? CreatedDate { get; set; }
}
}
The [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
attribute allows you to skip entity framework validation, but since your DateTime
prop is nullable
, you don't need it.
Create a new class
internal class AutoDateTimeMigrationSqlGenerator: SqlServerMigrationSqlGenerator //:NpgsqlMigrationSqlGenerator
{
protected override void Generate(AddColumnOperation addColumnOperation)
{
SetCreatedDateColumn(addColumnOperation.Column);
base.Generate(addColumnOperation);
}
protected override void Generate(CreateTableOperation createTableOperation)
{
SetCreatedDateColumn(createTableOperation.Columns);
base.Generate(createTableOperation);
}
private static void SetCreatedDateColumn(IEnumerable<ColumnModel> columns)
{
foreach (var columnModel in columns)
{
SetCreatedDateColumn(columnModel);
}
}
private static void SetCreatedDateColumn(PropertyModel column)
{
if (column.Name == "CreatedDate")
{
column.DefaultValueSql = "GETUTCDATE()";
}
}
}
In your Configuration.cs
file (the one with the migration configuration class that inherits from DbMigrationsConfiguration<>
) add the following line in the class constructor:
public Configuration()
{
AutomaticMigrationsEnabled = false;
SetSqlGenerator("System.Data.SqlClient", new AutoDateTimeMigrationSqlGenerator())
}
PS: Update-Database
after all this.