Created
April 24, 2021 22:35
-
-
Save westonpace/f1205a92818825109e920799a9db6b18 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Globalization; | |
using Microsoft.EntityFrameworkCore; | |
using Microsoft.EntityFrameworkCore.Design; | |
using Microsoft.Extensions.Configuration; | |
namespace Arena.Utilities | |
{ | |
public abstract class BaseDbContextFactory<T> : IDesignTimeDbContextFactory<T> where T : DbContext | |
{ | |
public T CreateDbContext(string[] args) | |
{ | |
var configuration = new ConfigurationBuilder() | |
.AddUserSecrets<BaseDbContextFactory<T>>() | |
.AddEnvironmentVariables() | |
.Build(); | |
var connectionStringTemplate = configuration["Database:ConnectionStringTemplate"]; | |
if (connectionStringTemplate == null) | |
{ | |
throw new Exception("No Database:ConnectionStringTemplate specified. Add it to the environment variables or the user secrets for the utilities project"); | |
} | |
var connectionString = string.Format(CultureInfo.InvariantCulture, connectionStringTemplate, GetDbName()); | |
var optionsBuilder = new DbContextOptionsBuilder<T>(); | |
optionsBuilder | |
.UseNpgsql(connectionString); | |
return CreateDbContext(optionsBuilder.Options); | |
} | |
protected abstract T CreateDbContext(DbContextOptions<T> options); | |
protected abstract string GetDbName(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment