Custom configuration provider and EF Core migrations
Following the Custom configuration provider guide I got the following error when adding migrations.
PM> Add-Migration -StartupProject: OurApp.Login.Web AppDbConfiguration
Build started...
Build succeeded.
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Invalid object name 'AppConfigurationValues'.
To undo this action, use Remove-Migration.
PM>
It turned out to be caused by calling the AddDbConfiguration extension method when creating the Host. The extension method is accessing the AppConfigurationValues DbSet and it doesn’t exist until the migration have been added. Just add an IsStartedWithMain property to Program and use that to indicate if beeing run from a migration.
public class Program
{
// Used to detect if run inside a migration since EF migrations won't run Main().
public static bool IsStartedWithMain { get; private set; }
public static int Main(string[] args)
{
IsStartedWithMain = true;
var host = Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureAppConfiguration((hostingContext, config) =>
{
if (IsStartedWithMain)
{
var configuration = config.Build();
var cs = configuration.GetConnectionString("DefaultConnection");
config.AddDbConfiguration(options => options.UseSqlServer(cs));
}
})
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
host.Run();
}
}