Database.EnsureCreated not working

c# entity-framework-core

Question

I'm playing around with Entity Framework 7 versions listed below

"EntityFramework.Core": "7.0.0-rc1-final",
"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
"EntityFramework.Commands": "7.0.0-rc1-final"

My DatabaseContext class is very simple

public class WorldContext : DbContext
{
    public DbSet<Trip> Trip { get; set; }
    public DbSet<Stop> Stop { get; set; }

    public WorldContext()
    {
        Database.EnsureCreated();
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var connectionString = Startup.Configuration["Data:WorldContextConnection"];

        optionsBuilder.UseSqlServer(connectionString);
        base.OnConfiguring(optionsBuilder);
    }
}

I'm experiencing a problem when hitting the Database.EnsureCreated method in the constructor. As far as I can understand, this method is supposed to make ensure that the database is created if it does not exist, otherwise it is supposed to do nothing. When I debug through my DatabaseContext class code I hit the breakpoint set on the Database.EnsureCreated method, when execution continues the breakpoint is hit a second time (This was not expected), so the DatabaseContext constructor is entered into twice for some reason. On the second hit the following exception is thrown

enter image description here

Even if the database exist, shouldn't the EnsureCreated method ignore it? Am I missing something here?

Accepted Answer

Do not call ensure created in your constructor, but call it once during app start



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why