Confusing Behavior of DbContext.Database.EnsureCreated in EF Core 2.1

.net-core c# entity-framework-core

Question

I am developing some code based on the tutorial found at https://docs.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:

  1. How does one check for database existence in EF Core 2.1?

  2. Is it safe to assume that the database exists after calling EnsureCreated without checking the return value?

1
0
10/14/2018 1:29:48 AM

Popular Answer

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.

That would violate .NET API Design Guidelines:

X DO NOT return error codes.
Exceptions are the primary means of reporting errors in frameworks.
✓ DO report execution failures by throwing exceptions.

https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/exception-throwing

Is it safe to assume that the database exists after calling EnsureCreated without checking the return value?

Yes.

1
10/4/2018 8:12:21 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow