【问题标题】:Run database migration before app start (.NET5, EF core 5)在应用启动前运行数据库迁移(.NET5、EF core 5)
【发布时间】:2021-10-02 10:39:06
【问题描述】:

我有 web 和 api 应用程序。在Startup.cs 中运行迁移似乎不是一个好主意,因为迁移需要运行一次,并且我的 API 和 WEB 项目同时部署。

应用程序是.NET core web 和.NET core api,创建了 docker 映像并在 linux 上运行。

我创建了执行迁移的 .net 核心 exe 应用程序,但我不知道将其合并到此场景中的最佳方式。

我的想法是在 docker web 映像启动之前运行该 dll,但问题是我有两个 docker 映像

或者可能从该迁移控制台应用程序创建 docker 映像并仅在成功时启动 web 和 api 容器

编辑:

我使用这个 docker 文件创建了 docker 镜像

FROM mcr.microsoft.com/dotnet/aspnet:5.0-buster-slim AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/sdk:5.0-buster-slim AS build
WORKDIR /src

COPY ["ef-migrations-cli/EfMigrationsCLI/EfMigrationsCLI/EfMigrationsCLI.csproj", "ef-migrations-cli/EfMigrationsCLI/EfMigrationsCLI/"]

RUN dotnet restore "ef-migrations-cli/EfMigrationsCLI/EfMigrationsCLI/EfMigrationsCLI.csproj"  --source "https://api.nuget.org/v3/index.json"
COPY . .

WORKDIR /src
COPY ["RED.Database.Server/RED.Database.Server.csproj", "RED.Database.Server/"]

COPY . .


WORKDIR "/src/ef-migrations-cli/EfMigrationsCLI/EfMigrationsCLI"
FROM build AS publish
RUN dotnet publish "EfMigrationsCLI.csproj" -c Release -o /app/publish

WORKDIR /src
WORKDIR "/src/RED.Database.Server"
FROM build AS publish2
RUN find /src/RED.Database.Server/RED.Database.Server.csproj -name *.csproj
RUN dotnet publish "/src/RED.Database.Server/RED.Database.Server.csproj" -c Release -o /app/publish

FROM base AS final

WORKDIR /app

COPY --from=publish2 /app/publish .

COPY --from=publish /app/publish .

ENV Server "please_set_Server_env_variable_when_docker_run"
ENV DatabaseName "please_set_DatabaseName_env_variable_when_docker_run"
ENV UserId "please_set_UserId_env_variable_when_docker_run"
ENV Password "please_set_Password_env_variable_when_docker_run"
ENV DatabaseContext "REDDatabaseContext"
ENV MigrationsAssembly "RED.Database.Server.dll"

ENTRYPOINT [ "sh", "-c", "dotnet EfMigrationsCLI.dll --userid=${UserId} --password=${Password} --databasename=${DatabaseName} --server=${Server} --databaseContext=REDDatabaseContext --migrationsAssembly=${MigrationsAssembly}" ]

我不喜欢的是 migrations.dll 和我的应用程序的包含迁移的 dll 在同一个图像中。

如何将它们分开?构建一个所有项目都将使用的通用迁移器镜像,然后创建单独的镜像来加载该镜像并构建必要的 myappsthatcontainsmigration.dll 文件并将该文件传递给第一个创建的容器

【问题讨论】:

    标签: c# .net docker deployment entity-framework-core


    【解决方案1】:

    我们不建议在应用程序启动过程中运行迁移,因为这种并发问题以及可能不适合正常运行的应用程序的权限需求。我们建议将数据库迁移作为应用程序部署的一部分进行,而不是首次运行。部署可以使用脚本(例如从迁移生成)或者可以直接针对生产数据库运行工具。在任何一种情况下,都以受控方式完成以避免并发,并在具有适当权限的环境中完成。

    Github Issue

    【讨论】:

      猜你喜欢
      • 2021-12-31
      • 2017-12-24
      • 2018-06-19
      • 2019-08-03
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 2019-04-11
      • 2020-10-02
      相关资源
      最近更新 更多