Reputation: 7092
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.
Upvotes: 6
Views: 2573
Reputation: 22790
For the official MS response, see Use SQLite for development, SQL Server for production
Upvotes: 1
Reputation: 5742
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.
Upvotes: 9