繁体   English   中英

EF6代码首先将CreatedDate和ModifiedDate列添加到现有数据库

[英]EF6 Code First add CreatedDate & ModifiedDate column to existing database

我正在尝试将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();
    }
}

任何帮助将不胜感激。

您启用了迁移吗? 如果没有,您可以在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();
   }
}

希望这对您有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM