在dotnet core 2中的不同环境中运行不同的数据库类型

时间:2017-09-14 17:25:52

标签: entity-framework sqlite asp.net-core entity-framework-6 .net-core

我想在开发中运行SQLite数据库,在生产中运行SQLServer Express数据库。

我们首先使用代码进行数据库迁移。

如何在每个环境中注入不同的dbcontext?

如何针对特定数据库运行迁移。例如。在开发中,我想要针对SQLite数据库运行迁移。

2 个答案:

答案 0 :(得分:8)

所以我想我找到了一个很好的方法来做到这一点。您可以使用ConfigureDevelopmentServices启动约定来添加SQLSite DbContext。所以,正如您将拥有的一些基本示例:

// Production "like" ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
    // Use Sql Server
    services.AddDbContext<SchoolContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("ProductionConnection")));
}

// Development ConfigureServices
public void ConfigureDevelopmentServices(IServiceCollection services)
{
    // Use SQL Lite
    services.AddDbContext<SchoolContext>(options =>
        options.UseSqlite(Configuration.GetConnectionString("DevelopmentConnection")));
}

如果碰巧只有另一个不同的上下文用于登台,你甚至可以进一步添加一个ConfigureStagingServices。为了避免复制和粘贴公共服务,您可以使用一个私有方法来注册公共服务,并且只有特定的服务才能使用单独的方法。

现在进行迁移,我从未测试过这个,但我最好的猜测是,如果你有正确的dbContext和正确的连接字符串,迁移将正常工作。您只需指向EF项目并运行它。

答案 1 :(得分:1)

有关 MS 的官方回复,请参阅 Use SQLite for development, SQL Server for production