EF6 Code First添加CreatedDate& ModifiedDate列到现有数据库

时间:2015-11-03 03:36:45

标签: c# entity-framework entity-framework-6

我尝试将CreatedDate和ModifiedDate列添加到现有数据库。我需要的是每次向表中添加一行时,CreatedDateModifiedDate将使用GETDATE()自动设置其值,这些之间的差异为ModifiedDate将继续每次修改行时都要更新。我一直在四处寻找并找到了复杂的答案。这是我的代码:

实体

public class Student
{
    public int StudentID {get; set;}
    public string Name {get; set;}
    //I want to add CreatedDate and ModifiedDate here
}

背景:

public class TestContext: DbContext
{
    public TestContext()
        : base("TestContext")
    {

    }

    public DbSet<Student> Students { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Student
        modelBuilder.Entity<Student>().HasKey(s => s.StudentID);
        modelBuilder.Entity<Student>().Property(s => s.Name).IsRequired();
    }
}

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您是否启用了迁移功能?如果没有,您可以在Package Manager Console中启用它。打开它并输入:

Enable-Migrations –EnableAutomaticMigrations

然后,在班级Student

public class Student
{
    public int StudentID {get; set;}
    public string Name {get; set;}
    public DateTime CreatedDate { get; set; }
    public DateTime ModifiedDate { get; set; }
}

返回Package Manager Console并输入:Update-Database -Verbose。刷新您的数据库,您将看到它们。

在控制器中,您可以通过TestContext访问它们,如下所示:

public ActionResult GETDATE(string id)
{
   using (var db = new TestContext())
   {
      var createDate = db.Students.SingleOrDefault(x => x.Id == id).CreateDate;
      //do something...
      return View();
   }
}

希望这对你有所帮助。