Skip to content

Instantly share code, notes, and snippets.

@tonysneed
Last active August 31, 2022 12:38
Embed
What would you like to do?
ProductsDbContextFactory3
public class ProductsDbContextFactory : IDesignTimeDbContextFactory<ProductsDbContext>
{
public ProductsDbContext CreateDbContext(string[] args)
{
// Get environment
string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
// Build config
IConfiguration config = new ConfigurationBuilder()
.SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "../EfDesignDemo.Web"))
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{environment}.json", optional: true)
.AddEnvironmentVariables()
.Build();
// Get connection string
var optionsBuilder = new DbContextOptionsBuilder<ProductsDbContext>();
var connectionString = config.GetConnectionString(nameof(ProductsDbContext));
optionsBuilder.UseSqlServer(connectionString, b => b.MigrationsAssembly("EfDesignDemo.EF.Design"));
return new ProductsDbContext(optionsBuilder.Options);
}
}
@allamgr
Copy link

allamgr commented Aug 31, 2022

This code maybe will fail for migration bundle for production environment, since the EFDesifnDemo.Web folder might not exists, you can have a fallback folder to prevent the error and support ef migrations bundle

internal static class IConfigurationRootExtensions
    {
        public static IConfigurationBuilder AddBasePath(this IConfigurationBuilder builder)
        {
            var currentDirectory = Directory.GetCurrentDirectory();
            var startupProjectPath = Path.Combine(currentDirectory, "../EfDesignDemo.Web");
            var basePathConfiguration = Directory.Exists(startupProjectPath) ? startupProjectPath : currentDirectory;

            return builder.SetBasePath(basePathConfiguration);
        }
    }

And just call AddBasePath instead of setBasePath

IConfiguration config = new ConfigurationBuilder()
            .AddBasePath()

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