[英]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. 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.所以我已经有一个DbContext
,所有的实体,我就是无法弄清楚如何根据我的 API 项目中已经存在的上下文在 SQL 服务器映像中构建数据库。
docker-compose
file for reference: docker-compose
文件供参考:
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上下文和实体: 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()有效的修复是使用实体框架允许的功能,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将以下代码行添加到 Startup 中的 Configure 方法会在容器中创建架构和数据库(如果尚不存在)
// 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.