Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Core (1.0.0) Migrations On Azure App Services

We have a web app (Net Core 1.0.0-preview2-003121) deployed to an Azure App Service and we're struggling to deploy the migrations.

In RC1/2 it was possible to do the migrations with an ef.cmd file that seemed to be automagically there, namely we could use this file to run

dnx ef database update 

but this is gone.

dotnet ef is not installed in the Azure App Service itself, so this is not an option.

Any ideas that don't involve running the migrations from code/deploying them from visual studio?

We're trying to build a continuous deployment pipeline and I'd rather avoid forcing the deployment of migrations from code.

MY google fu is clearly failing me here as it can't for the life of me find anything and i can't be the only one trying to deploy the migrations on the server

TIA

like image 902
ManyRootsofAllEvil Avatar asked Oct 30 '22 20:10

ManyRootsofAllEvil


1 Answers

What we ended up doing is:

On the build side we generate an idempotent database creation script:

dotnet ef migrations script --idempotent --output migrations.sql  --context  ApplicationContext

Where ApplicationContext is the name of your EF context and migrations.sql is the sql script file name.

Then on deployment side we have a small powershell script that effectively runs the migrations.sql script

param(
[Parameter(Mandatory)]
[string]$server,
[Parameter(Mandatory)]
[string]$dbname,
[Parameter(Mandatory)]
[string]$dbadmin,
[Parameter(Mandatory)]
[string]$dbpassword,
[Parameter(Mandatory)]
[string]$migrationPath
)

function Deploy-Migrations ($migrationPath,$DBSettings)
{
   #Setting up database connection
   $connection = New-Object System.Data.SqlClient.SqlConnection
   $connection.ConnectionString = [string]::Format("Data Source=tcp:{0}.database.windows.net,1433;Initial Catalog={1};User Id={2}@{0};Password={3};MultipleActiveResultSets=True", $DBsettings['sqlServerName'], $DBsettings['databasename'],$DBsettings['adminAccount'], $DBsettings['adminPassword']) 

    try
    {
        $connection.Open();

         $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
         $SqlCmd.Connection = $connection
         $query = Get-Content $migrationPath
         $sqlCmd.CommandText = $query.Replace("GO","") # This is required to prevent "syntax" complaints
         $sqlCmd.ExecuteNonQuery()

         Write-Host "Migration Deployed" 
    }
    Catch
    {

        Write-Error "oops ... PAnic ... $($_.Exception.Message) on $($_.Exception.ItemName)"
        break
    }
    Finally
    {
        $connection.Close()
    }  
 }

$DBSettings = @{"sqlServerName"=$server; "databasename"=$dbname;    "adminAccount"=$dbadmin; "adminPassword"=$dbpassword }

Deploy-Migrations $migrationPath $DBSettings
like image 186
ManyRootsofAllEvil Avatar answered Nov 09 '22 06:11

ManyRootsofAllEvil