I am developing some code based on the tutorial found at https://learn.microsoft.com/en-us/aspnet/core/data/ef-rp/intro?view=aspnetcore-2.1&tabs=visual-studio. Specifically, I am looking at the following snippet in the file Program.cs.
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<SchoolContext>();
context.Database.EnsureCreated();
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred creating the DB.");
}
}
host.Run();
}
I am using the Contoso University data model as presented in the tutorial with a ConnectionString defined in the appSettings.json file using localdb. I modified the code as follows:
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
bool dbCreated = false;
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<SchoolContext>();
dbCreated = context.Database.EnsureCreated();
if (dbCreated) DbInitializer.Initialize(context);
} // end try
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred creating the DB.");
} // end catch (Exception ex)
} // end using (var scope = host.Services.CreateScope())
host.Run();
} // end public static void Main(string[] args)
The behavior I observe concerns the variable, dbCreated, initialized to false. If the database is not there, it is created and the EnsureCreated call returns true. If it exists, is unchanged(false). I did not expect this behavior. I would expect the call would return true, if the database already exists or if it was successfully created. If the creation fails it would return false or throw an exception or both. In EF5 there was a call, context.Database.Exists(). See Entity Framework Code First check Database exist. This does not seem to be available in EF Core 2.1. I have two questions:
How does one check for database existence in EF Core 2.1?
Is it safe to assume that the database exists after calling EnsureCreated without checking the return value?