Andre Lombaard
Andre Lombaard

Reputation: 7105

Database.EnsureCreated not working

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?

Upvotes: 1

Views: 4172

Answers (1)

ErikEJ
ErikEJ

Reputation: 41769

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

Upvotes: 4

Related Questions