简体   繁体   中英

How can I create the SQL Server database scheme for a Docker image based on an existing DbContext with Entity Framework?

Started working with Docker images recently, and my main problem is that while my docker-compose can spin up the api, and the database I need, what it lacks is the actual scheme of the database that the entities within my API project look for when getting data.

So I have a DbContext already, all the entities, and I namely cant figure out for the life of me how to build the database in the SQL Server image based on the context that is already in my API project.

docker-compose file for reference:

networks:
  event_localhost:
services:
  api:
    build:
      context: ..
      dockerfile: .docker/Dockerfile
    image: spc-eventapi
    depends_on:
      - db
    ports:
      - 8000:80
    networks:
      - event_localhost
    environment:
      ConnectionStrings__EventDb: 'Server=db,1433;Database=master;User Id=sa;Password=Pass@word;'
  db:
    image: mcr.microsoft.com/mssql/server
    networks:
      - event_localhost
    environment:
      SA_PASSWORD: 'Pass@word'
      ACCEPT_EULA: "Y"
    ports:
      - "1433:1433"
version: '3.9'

Context and entities: https://github.com/SantaPoneCentralDev/santaponecentral/tree/Docker/SPC-2021/api/event/event/Event.Data/Entities

The fix that worked was using the functions that entity framework allows, being.EnsureCreated()

Adding the following lines of code to the Configure method in Startup creates the schema and DB in the container if it doesn't already exist

            // Ensures DB is created against container
            IServiceScopeFactory serviceScopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
            using IServiceScope serviceScope = serviceScopeFactory.CreateScope();
            SantaPoneCentralDatabaseContext dbContext = serviceScope.ServiceProvider.GetService<SantaPoneCentralDatabaseContext>();
            dbContext.Database.EnsureCreated();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM