1

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; }
    }
}
Dismissile
  • 32,564
  • 38
  • 174
  • 263
Dave
  • 263
  • 6
  • 23
  • Why are you against using `library.CreatedDate = (DateTime)DateTime.Now;` ? – Matias Cicero Dec 18 '14 at 17:51
  • Hi, I am not against the above line.I tried it in my Post Method of the controller but still null is saved in CreatedDate,I debugged it datetime can be seen but null is saved. – Dave Dec 20 '14 at 09:50
  • [HttpPost] public ActionResult Create(Library library) { try { if (ModelState.IsValid) { library.CreatedDate = (DateTime)DateTime.Now; db.Librarys.Add(library); db.SaveChanges(); return RedirectToAction("Index"); } return View(library); } catch { return View(); } } Where do I write it,please guide. – Dave Dec 20 '14 at 09:53

1 Answers1

1

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.

Cristi Pufu
  • 9,002
  • 3
  • 37
  • 43