10

On a Mac I have a Net Core 2.1 Class Library with a few Entity Framework migrations.

I need to use Docker to run SQL Server and update the database with the previews migrations.

I added a docker-compose.yml file to my project:

docker-compose.yml
src
  data
    project.data.csproj

The docker-compose.yml file is the following:

services:
  data:
    build: .
    depends_on:
      - database
  database:
  image: "microsoft/mssql-server-linux"
  environment:
    SA_PASSWORD: "Pass.word123"
    ACCEPT_EULA: "Y"

At the moment this is not working.

How can I run EF Core migrations on SQL Server using docker in a Mac?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • 2
    Off the top of my head there's two ways, have Docker execute `dotnet ef database update` during the container build or at run time you can use `Database.Migrate()`, which would suit your case? – Adam Vincent Nov 08 '18 at 01:35
  • I use dotnet ef database update – Miguel Moura Nov 08 '18 at 11:45
  • What you're asking for is in discussion [in this issue on GitHub](https://github.com/dotnet/dotnet-docker-samples/issues/89) – Adam Vincent Nov 08 '18 at 13:05
  • It's a good question, but I don't think there's a solid solution at this time. – Adam Vincent Nov 08 '18 at 13:06
  • As @AdamVincent suggested, runtime migration looks like natural solution to me. If you for some reason want to run migration by hand, add some parameter to program/appsettings to control the behaviour – Karel Křesťan Oct 25 '20 at 18:04
  • I finally found a solution to this problem here in this post: https://stackoverflow.com/questions/60129303/using-dotnet-ef-with-docker-and-asp-net-core-3-1?rq=3 – Vladislav Khomchenko Jun 23 '23 at 13:37

1 Answers1

3

You need to add below lines in Confiure of startup file. It will executed when the application is started. It will update all the migration files to database.

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

This worked for me.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Gopi
  • 92
  • 1
  • 10