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

后端 未结 8 2106
北海茫月
北海茫月 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:46

    As already said, replace the AddColumn and DropColumn that is automatically generated with RenameColumn.

    Example:

    namespace MyProject.Model.Migrations
    {
        using System;
        using System.Data.Entity.Migrations;
    
        public partial class RenameMyColumn : DbMigration
        {
            public override void Up()
            {
                // Remove the following auto-generated lines
                AddColumn("dbo.MyTable", "NewColumn", c => c.String(nullable: false, maxLength: 50));
                DropColumn("dbo.MyTable", "OldColumn");
    
                // Add this line
                RenameColumn("dbo.MyTable", "OldColumn", "NewColumn");
            }
    
            public override void Down()
            {
                // Remove the following auto-generated lines
                AddColumn("dbo.MyTable", "OldColumn", c => c.String(nullable: false, maxLength: 50));
                DropColumn("dbo.MyTable", "NewColumn");
    
                // Add this line
                RenameColumn("dbo.MyTable", "NewColumn", "OldColumn");
            }
        }
    }
    

提交回复
热议问题