Skip to content

Instantly share code, notes, and snippets.

@bforrest
Last active May 1, 2020 14:24
Show Gist options
  • Save bforrest/f714343befa8000eeb36b2fb61bb292d to your computer and use it in GitHub Desktop.
Save bforrest/f714343befa8000eeb36b2fb61bb292d to your computer and use it in GitHub Desktop.
EF Core connections and DbContext Designtime factory
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(){}
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options): base(options){}
}
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<AppicationDbContext>
{
readonly string cnString;
public ApplicationDbContextFactory()
{
var baseDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
baseDir = baseDir.Replace("file:\\", "");
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(baseDir) // Directory where the json files are located
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
#if LOCAL
.AddJsonFile($"appsettings.local.json", optional: true, reloadOnChange: true)
#else
.AddJsonFile($"appsettings.development.json", optional: true, reloadOnChange: true)
#endif
.Build();
cnString = configuration.GetConnectionString("DbConnectionString");
}
public AppicationDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<AppicationDbContext>();
optionsBuilder.UseSqlServer(cnString, b => b.MigrationsAssembly("EF-Assembley"));
return new eArchiveContext(optionsBuilder.Options);
}
}
public class Program
{
public static async Task Main(string[] args)

{
var environment = arguments["-env"]?.ToLower() ?? "development";
var configBuilder = new ConfigurationBuilder()
.SetBasePath(baseDir)
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{environment.ToLower()}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
......
}
public static void Configure(HostBuilderContext hostContext, IServiceCollection services)
{
var cnString = configuration.GetConnectionString("DbConnectionString");
services.AddDbContext<DbContext, ApplicationDbContext>(x => x.UseSqlServer(cnString));
...
}
}
@bforrest
Copy link
Author

bforrest commented May 1, 2020

Program is the self-host
ApplicationDbContext lives in a library file and the dotnet ef tooling is cranky about that so I created a separate console application to create/run the migrations. It works well but has to have the -s or be executed from the same directory as that project

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment