using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.Extensions.Configuration; using System; using System.IO; namespace Benday.EfCore.DesignTimeDbContextFactorySample { public abstract class DesignTimeDbContextFactoryBase : IDesignTimeDbContextFactory where TContext : DbContext { public TContext CreateDbContext(string[] args) { return Create( Directory.GetCurrentDirectory(), Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")); } protected abstract TContext CreateNewInstance( DbContextOptions options); public TContext Create() { var environmentName = Environment.GetEnvironmentVariable( "ASPNETCORE_ENVIRONMENT"); var basePath = AppContext.BaseDirectory; return Create(basePath, environmentName); } private TContext Create(string basePath, string environmentName) { var builder = new ConfigurationBuilder() .SetBasePath(basePath) .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{environmentName}.json", true) .AddEnvironmentVariables(); var config = builder.Build(); var connstr = config.GetConnectionString("default"); if (String.IsNullOrWhiteSpace(connstr) == true) { throw new InvalidOperationException( "Could not find a connection string named 'default'."); } else { return Create(connstr); } } private TContext Create(string connectionString) { if (string.IsNullOrEmpty(connectionString)) throw new ArgumentException( $"{nameof(connectionString)} is null or empty.", nameof(connectionString)); var optionsBuilder = new DbContextOptionsBuilder(); Console.WriteLine( "MyDesignTimeDbContextFactory.Create(string): Connection string: {0}", connectionString); optionsBuilder.UseSqlServer(connectionString); DbContextOptions options = optionsBuilder.Options; return CreateNewInstance(options); } } public class MyDbContext : DbContext { public MyDbContext(DbContextOptions options) : base(options) { } // public DbSet Persons { get; set; } // public DbSet Notes { get; set; } } public class MyDbContextDesignTimeDbContextFactory : DesignTimeDbContextFactoryBase { protected override MyDbContext CreateNewInstance( DbContextOptions options) { return new MyDbContext(options); } } }