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 yourDateTime
prop isnullable
, you don't need it.Create a new class
In your
Configuration.cs
file (the one with the migration configuration class that inherits fromDbMigrationsConfiguration<>
) add the following line in the class constructor:PS:
Update-Database
after all this.