C#C
C#3y ago
33 replies
Johannes M

✅ EF Core migrations at design time using Clean Architecture - .NET 7

I am currently working on a project using clean architecture with Blazor Server. I have my connection string inside the web project but I would like to create my db migrations inside the infrastructure project where my DbContext is sitting. I have a method that will run any outstanding migrations on project startup but when I want to manually create my migrations or update my database using add-migration or update-database. Each time I try this I get an error that it cannot create my DbContext and I should look at the design time on the MS docs. My way around this was creating a configbuilder inside of the infra project and adding a new appsettings.json file and it worked,

Is there a way in which I don't have to create a config builder inside my context factory referencing an appsettings.json file inside of the infra project?
When the project runs I am able to inject the connection string via the DI container and IOptions but this does not work when the project is not running.

public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
    public ApplicationDbContext CreateDbContext(string[] args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.Development.json")
                .Build();

        var builder = new DbContextOptionsBuilder<ApplicationDbContext>();
        builder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"),
            optionsBuilder => optionsBuilder.MigrationsAssembly(typeof(ApplicationDbContext).GetTypeInfo().Assembly.GetName().Name));
        return new ApplicationDbContext(builder.Options);
    }
}
Was this page helpful?