MikePR
MikePR

Reputation: 2986

How to enable Code First migration in Azure

I'm developing an MVC 5 project in VS 2013 using the Code First Migration approach. At the beginning all was working OK both locally and the 1st time I deployed the MVC site to azure.

In both places (locally and Azure) the Identity tables were created correctly:

The issue I'm facing is when I added two new columns: Name and LastName to store this data for the user. Then, I Update my schema using First Code Migration. It was updated correctly in my local machine. The new columns were added to the AspNetUser table.

However, when I deployed it to Azure, that table doesn't contained the new columns yet. Which is causing that I get the error:

Server Error in '/' Application.

Invalid column name 'Name'.
Invalid column name 'LastName'.
Invalid column name 'Name'.
Invalid column name 'LastName'.
Invalid column name 'Name'.
Invalid column name 'LastName'.

So, how could I enable the code first migration to my MVC project in Azure? So that, when I deploy it from Visual Studio the data base schema gets updated in Azure as well.

Upvotes: 2

Views: 849

Answers (1)

Danielle
Danielle

Reputation: 3839

Here are 2 solutions:

1. Using Update-Database from the Package Manager Console:

Run the following from the Package Manager Console:

Update-Database 
-TargetMigration {YourMigration} 
-ConnectionString "Server=tcp:{your server name}.database.windows.net,1433;
                   Database={your db};
                   User ID={your user}@{your server};
                   Password={your password};
                   Trusted_Connection=False;
                   Encrypt=True;
                   Connection Timeout=30;" 
-ConnectionProviderName "System.Data.SqlClient"

Replace the relevant server name, user name, db and password data from your Azure Portal Connection String

2. Run migration from code:

Add the following to Application_Start in Global.asax

protected void Application_Start()
{
    //....

    // Running Migrations from Code:
    var configuration = new Configuration();
    var migrator = new DbMigrator(configuration);
    migrator.Update();
}

Calling the Update method will update the target database to the latest migration.

Taken from: https://romiller.com/2012/02/09/running-scripting-migrations-from-code/

Upvotes: 2

Related Questions