dsingh23
dsingh23

Reputation: 195

Entity Framework(Code-First Migrations): While Renaming a column do I need to make a change in the model as well?

I have to rename 2 columns in my database. I am working with Code-first migrations. So, I added the following code to the up() an down() methods in the migration file that was created after I ran the 'add-migration migration_name' command in Package Manager Console.

Code

 public override void Up()
     {
       RenameColumn(table: "dbo.Table1", name: "oldColumnName", newName: "newColumnName");
       RenameColumn(table: "dbo.Table1", name: "oldColumnName2", newName: "newColumnName2");
     }

    public override void Down()
    {
       RenameColumn(table: "dbo.Table1", name: "oldColumnName2", newName: "newColumnName2");
       RenameColumn(table: "dbo.Table1", name: "oldColumnName", newName: "newColumnName");
     }
}

I did not make any change to my model since, if I ADD OR DELETE any property within the model it would add or delete those columns.

My question is after running the update-database command in Package Manager Console, will the model be itself updated or do I need to make a change and if yes, then what change and when do I make that change in the model.

Upvotes: 2

Views: 1105

Answers (2)

Jesus Angulo
Jesus Angulo

Reputation: 2666

If you change the generated migration code, then you need to ensure that your mapping code is in sync with your database.

If you don't have mapping classes and you use convention over configuration then you need to change your model.

If you have mapping code or a separated mapping class then you need to update your mapping code to be in sync with your database.

Upvotes: 1

SeanG80
SeanG80

Reputation: 169

You can add the column name attribute to your model, Type is not required. This is not required but if you run into any mapping issues this should correctly map the column.

[Column(“BlogDescription", TypeName="ntext")] 
public String Description {get;set;}

Using Code First Name was:

public String FName {get; set;}

Changed to

public String FirstName {get; set;}

Then I run command add-migration UpdateColumnName followed by command update-database everything should map correctly.

Upvotes: 0

Related Questions