C
C#6mo ago
Spaxter

DbContextFactory check for valid connection on app startup

I have a .NET app where I'm currently using EF Core's DbContextFactory with Postgres. However I noticed that no matter what host I set in my connection string the app starts normally and no errors are thrown. Is it possible to validate the connection at startup?
builder.Services.AddDbContextFactory<DataContext>(options =>
{
options.UseNpgsql(postgresOptions.ConnectionString);
}
builder.Services.AddDbContextFactory<DataContext>(options =>
{
options.UseNpgsql(postgresOptions.ConnectionString);
}
1 Reply
Spaxter
SpaxterOP6mo ago
I ended up solving it like this Program.cs
var contextFactory = app.Services.GetRequiredService<IDbContextFactory<DataContext>>();
using (var context = contextFactory.CreateDbContext())
{
context.Database.EnsureCreated();
}
var contextFactory = app.Services.GetRequiredService<IDbContextFactory<DataContext>>();
using (var context = contextFactory.CreateDbContext())
{
context.Database.EnsureCreated();
}
Want results from more Discord servers?
Add your server