Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run different database types in different environments in dotnet core 2

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.

like image 618
Ryan Walls Avatar asked Dec 24 '22 14:12

Ryan Walls


2 Answers

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 =>
        options.UseSqlServer(Configuration.GetConnectionString("ProductionConnection")));
}

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

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.

like image 58
jpgrassi Avatar answered Dec 26 '22 02:12

jpgrassi


For the official MS response, see Use SQLite for development, SQL Server for production

like image 37
RickAndMSFT Avatar answered Dec 26 '22 02:12

RickAndMSFT