如何 运行 在 Entity Framework Core 中先使用代码更新数据库?

How to run Update Database using Code first in Entity Framework Core?

我从visual studio 运行 Update-Database 创建了一个数据库,它工作正常。我已经在生产服务器上发布了该应用程序。但是我不能 运行 Update-Database 那里。那么在没有visual studio的服务器上怎么办呢?

我想在应用程序第一次启动时创建它。但是我没有得到任何参考或示例代码。

我正在使用 .net core 2.0。

首先我要警告你,我不知道下面的代码会产生什么后果,因为我对Abp的架构了解不够

在ProjectName.Web.Mvc项目中,在ConfigureServices方法中,添加如下代码:

public IServiceProvider ConfigureServices(IServiceCollection services) {

    // other stuff

    string connectionString = _appConfiguration
            .GetConnectionString("Default");

    services.AddDbContext<YouDbContextTypeName>(opt => 
        opt.UseSqlServer(connectionString)
    );

    // other stuff
}

在同一个文件的Configure方法中,添加如下代码:

public void Configure(
    IApplicationBuilder app, 
    IHostingEnvironment env, 
    YouDbContextTypeName context) {

    context.Database.Migrate();

    // other stuff
}

您可以 运行 在您的 'Test' Db 中针对您的开发 Db 所做的更改脚本。要生成脚本,您可以 运行 这会创建一个文件 运行 作为部署阶段的一部分。

dotnet ef migrations script -i -o "C:\<your-path>\<your-filename>.sql"

生成的脚本本质上是所有 'Up' 迁移的累积。该脚本是 'idempotent',因为它仅在迁移尚未应用于数据库时才应用迁移。

REF: dotnet CLI