Search code examples
.netazureef-code-firstdotnet-cli

How to apply database code first migrations in an azure deployed application?


I just deployed an application into an azure App Service. My project does has migrations to be applied. But I was not able to apply them by using azure app command line

dotnet ef database update

D:\home\site\wwwroot> No executable found matching command "dotnet-ef"

How can I apply them remotely?


Solution

  • For dotnet-ef, I assumed that you are talking about Entity Framework Core. I have tried to run dotnet ef database update under D:\home\site\wwwroot of KUDU and Package Manager Console of VS, I could encounter the same issue as you mentioned.

    I found a similar issue No executable found matching command "dotnet-ef":

    DotNet CLI can only resolve "dotnet-ef" when it is within the project directory.

    I could run the commands dotnet ef migrations add, dotnet ef database update via Powershell. For detailed command usage, you could follow EF Core .NET Command-line Tools.

    How to apply database code first migrations in an azure deployed application?

    Per my understanding, you could not do that. You may need to manually run update-database as vivek nuna answered under Package Manager Console of VS, or you could use Powershell and cd to your project directory, and execute dotnet ef database update to apply any pending migrations for your context to the database, then deploy your application to azure web app.

    Additionally, EF does not support Automatic migrations, you may need to manually execute Add-Migration or dotnet ef migrations add for adding migration files. You could explicitly execute the command to apply the migrations, also you could apply migrations in your code. And you could add the following code in the Configure method of Startup.cs file:

    using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
    {
        scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Database.Migrate();
    }
    

    Moreover, you could also follow this similar issue.