Tell EF to automatically compute and insert the current date time when the row is created?

本秂侑毒 提交于 2020-01-25 04:20:06

问题


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; }
    }
}

回答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.



来源:https://stackoverflow.com/questions/27552573/tell-ef-to-automatically-compute-and-insert-the-current-date-time-when-the-row-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!