c# - 在 Docker 镜像中使用 ASP.Net Core 时应用 Entity Framework 迁移

标签 c# docker asp.net-core entity-framework-core

我有一个 ASP.Net Core 应用程序,它使用 Entity Framework 和 Sqlite。我正在构建一个 Docker 镜像来部署它。

ASP.Net Core 应用程序在使用 VS Code 调试时运行良好,但在 Docker 容器中运行时出现错误:

SqliteException: SQLite Error 1: 'no such table: MyTable'.

我认为这是因为我需要在构建 Docker 镜像时运行 Entity Framework 迁移。我已将 dotnet ef database update 添加到我的 Dockerfile,如下所示:

FROM microsoft/dotnet:sdk AS build-env
WORKDIR /app

COPY *.csproj ./
RUN dotnet restore

COPY . ./
RUN dotnet publish -c Release -o out

RUN dotnet ef database update

FROM microsoft/dotnet:aspnetcore-runtime
WORKDIR /app
COPY --from=build-env /app/out .
ENTRYPOINT ["dotnet", "MyApplication.dll"]

图像构建没有错误。但是,当我创建一个容器并查看数据库时,它是空的,没有任何表。

在构建 Docker 镜像时,使用 Entity Framework 设置数据库的正确方法是什么?

最佳答案

对于 .net 6 上的任何人,我在 Program.cs 文件中的 app.Run() 之前使用它在启动时应用迁移

using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;

    var context = services.GetRequiredService<ApplicationDbContext>();
    if (context.Database.GetPendingMigrations().Any())
    {
        context.Database.Migrate();
    }
}

关于c# - 在 Docker 镜像中使用 ASP.Net Core 时应用 Entity Framework 迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55970148/

相关文章:

c# - 如何通过友好名称打开串口?

c# - 带委托(delegate)的事件处理程序

c# - 已建立的连接被主机中的软件中止

docker - 将大文件添加到Docker构建中会导致EOF异常

docker - 如何将更新的 Docker 镜像部署到 Amazon ECS 任务?

C# P/调用数组数组

docker - 使用哪个GCP Compute Engine实例来构建Docker镜像?

c# - 错误 CS1061 : 'DbSet<T>' does not contain a definition for 'FromSql' and no extension method 'FromSql' accepting a first argument of type 'DbSet<T>'

c# - 在 ASP.net 核心应用程序的强类型配置类中使用 System.Uri

asp.net-core - ASP.NET CORE 2.1 服务器调试时超时