Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename a column in EF with Code First

i renamed a column in my class. It looked like this.

public class clsClassForStackoverflow
{
   [Column(TypeName = "varchar"), StringLength(150)]
   public string Name { get; set; }

Because of a change in the structure i had to rename it. So i deleted that row and added the new propertie. After that i created a new migration file to prepare my database update and in the file he wanted to delete the old column and add the new one. Well i changed the drop to a rename because there is still data in the database. With a drop it would be gone.

The new migration file:

public partial class _100126_2 : DbMigration
{
    public override void Up()
    {
        RenameColumn("dbo.tbClassForStackoverflow", "ClassForStackoverflow_Name",   "ClassForStackoverflow_NewName");
    }

    public override void Down()
    {
        RenameColumn("dbo.tbClassForStackoverflow", "ClassForStackoverflow_NewName", "ClassForStackoverflow_Name");
    }
}

After launching the database update i looked into my class and the propertie didnt changed. Its still named "Name" and not "NewName". How can i change that without let EF thinking i deleted and added a column?

like image 891
Cataklysim Avatar asked Sep 01 '25 01:09

Cataklysim


1 Answers

You need to do this change in the following order:

  1. Rename the Name property in your Entity to NewName
  2. Add a new migration to your project
  3. Change the migration to do the rename instead of the Drop/Create, BUT only change the content of the Up/Down method
  4. Compile and run the migration

This is how I did it several times already without problems. Important is to not touch the model snapshot associated with the migration when its created.

P.S.: If I remember correctly EF even detects renames if some (to me unknown) constraints are met, because I think it wasn't always necessary to even change the migration when doing a simple property/column rename.

like image 115
Christoph Fink Avatar answered Sep 02 '25 13:09

Christoph Fink