jaredcnance jaredcnance - 6 days ago 5
C# Question

.Net Core - Change database migrations depending on environment

So, I'm trying to figure out what the golden path is for running an application against a PostgreSQL database in development and a SQL Server database in production. The difficult part is that the migrations will be different. Currently, my approach is like this:

public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(SetDbContextOptionsForEnvironment, ServiceLifetime.Transient);
}

private void SetDbContextOptionsForEnvironment(DbContextOptionsBuilder options)
{
if(_environmentName == "production") {
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]);
}
else {
options.UseNpgsql(Configuration["Data:DefaultConnection:ConnectionString"]);
}
}


Is the preferred way to keep the migrations in a separate assembly and specify that assembly in the options? So then I need to have multiple definitions of the same DbContext in those assemblies as well?

Answer

After thinking on this for quite a while, I believe that this is an anti-pattern. Regardless of my particular use case (postgres in dev, SQL Server in prod), I think it is frowned upon to use different database systems for different environments as there may be unexpected issues after deployment. Best to stick with the same one for development and production.