使用EF Code First生成模型,如何让时间字段由数据库自动生成

  1. 场景:保存记录时需要时间字段,该时间如果由前台通过DateTime.Now产生,存在风险,比如修改客户端的系统时间,就会伪造该记录的生成时间。因此,需要在保存记录时,由后台自动赋予具体的时间。
  2. 实现方法:

1)完成模型

public class Record
{
    .....//其他字段
    public DateTime Date{get;set;}
}

2) 使用add-migration

3) 在VS生成的Migration文件中修改该字段

修改前:

namespace ***.Migrations
{
    public partial class Init : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            ......//其他表的信息
            migrationBuilder.CreateTable(
                name: "Records",
                columns: table => new
                {
                    ......//其他字段的信息
                    Date = table.Column<DateTime>(nullable: false),
                    ......//其他字段的信息
                 });
            ......//其他表的信息
        }
        ......    
    }
}

修改后(涂黄部分):

namespace ***.Migrations
{
    public partial class Init : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            ......//其他表的信息
            migrationBuilder.CreateTable(
                name: "Records",
                columns: table => new
                {
                    ......//其他字段的信息
                    Date = table.Column<DateTime>(nullable: false, defaultValueSql:"GETDATE()"),
                    ......//其他字段的信息
                 });
            ......//其他表的信息
        }
        ......    
    }
}

4)使用update-database完成迁移

5)程序中涉及到该时间时,可以不用理会,context.SaveChanges()时,在数据库中可以自动生成保存的时间。即便使用Date = DateTime.Now给该字段添加了时间,保存时该时间也会被忽略。

猜你喜欢

转载自www.cnblogs.com/jqdy/p/11254065.html
今日推荐