How to rename a database column in Entity Framework 5 Code First migrations without losing data?

后端 未结 8 2111
北海茫月
北海茫月 2021-01-30 10:25

I got the default ASP.NET MVC 4 template successfully running with EF 5.0 Code First Migrations. However, when I update a model property name, the corresponding table column dat

8条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-30 10:47

    you have 2 steps to rename column in code first migration

    1. The first step,you add ColumnAttribute above your column which are changed, and then update-database command

    [Column("Content")]
    public string Description { set; get; }

    1. The second step,

      • add-migration yournamechange command in order to create a partial class DbMigration.

      • add into up and down method here

    RenameColumn("yourDatabase","name","newName");

    public override void Up()
      {
            RenameColumn("dbo.your_database", "oldColumn",          
           "newColumn");
      }
    
    
    public override void Down()
      {
            RenameColumn("dbo.your_database", "newColumn", 
            "oldColumn");
      }
    

    Because when you connect, your database and model class will communicate via name_column at database and name_type at property method in model above.

提交回复
热议问题