告诉EF自动计算并插入创建行时的当前日期时间?

时间:2014-12-18 17:41:36

标签: entity-framework datetime model-view-controller

我希望在插入新行时插入当前日期时间 我正在使用EF 6,MVC 5的Code First Approach 搜索后我得到了这个

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]  
public DateTime? CreatedDate { get; set; }

它必须写在Models类中,但是当插入新记录时,NULL被保存在DB中,我注意到这只是CreatedDate的声明,在哪里写CreatedDate = DateTime.Now 或任何其他方式来解决它 我的整个模型

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 个答案:

答案 0 :(得分:1)

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]属性允许您跳过实体框架验证,但由于您的DateTime道具是nullable,因此您不需要它。

创建一个新类

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()";
            }
        }
    }

Configuration.cs文件(具有继承自DbMigrationsConfiguration<>的迁移配置类的文件)中,在类构造函数中添加以下行:

public Configuration()
{
      AutomaticMigrationsEnabled = false;
      SetSqlGenerator("System.Data.SqlClient", new AutoDateTimeMigrationSqlGenerator())
}

PS:Update-Database完成所有这些。