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

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

    like +Josh Gallagher said, you can use up() for doing things like:

    public override void Up()
            {
    
                RenameColumn("dbo.atable","oldname","newname");
                AddColumn("dbo.anothertable", "columname", c => c.String(maxLength: 250));
    
            }
    

    i've found this a good help in gettin into migration ;)

    0 讨论(0)
  • 2021-01-30 10:56

    You can get the migration to call RenameColumn for you if you do this:

    [Column("NewName")]
    public string OldName { get; set; }
    

    Here is the generated migration:

        public override void Up()
        {
            RenameColumn(table: "Schema.MyTable", name: "OldName", newName: "NewName");
        }
    
        public override void Down()
        {
            RenameColumn(table: "Schema.MyTable", name: "NewName", newName: "OldName");
        }
    

    If you want your property and DB column to be the same name, you can rename the property later and remove the Column attribute.

    0 讨论(0)
提交回复
热议问题