Run different database types in different environments in dotnet core 2

.net-core entity-framework entity-framework-6 sqlite


I want to run a SQLite database in development and a SQLServer Express database in production.

We are using code first with database migrations.

How do I inject a different dbcontext in each environment?

How do I run migrations against a specific database. E.g. In development I'll want to run migrations against the SQLite database.

9/14/2017 5:25:51 PM

Accepted Answer

So I guess I found a nice way for you to do that. You can use the ConfigureDevelopmentServices startup convention to add your SQLSite DbContext. So, just as some basic example you would have:

// Production "like" ConfigureServices
public void ConfigureServices(IServiceCollection services)
    // Use Sql Server
    services.AddDbContext<SchoolContext>(options =>

// Development ConfigureServices
public void ConfigureDevelopmentServices(IServiceCollection services)
    // Use SQL Lite
    services.AddDbContext<SchoolContext>(options =>

You can even go further and add a ConfigureStagingServices if you happen to have another different context for staging only. To avoid copy and pasting of common services, you could have a private method that register the common services and have the separate ones only with specific stuff.

Now for the migrations, I never tested this but, my best guess is if you have the correct dbContext and the correct connection string, the migrations will work fine. You just point to the EF project and run it.

9/15/2017 7:50:17 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow