Home Database.EnsureCreated() not creating tables
Reply: 0

Database.EnsureCreated() not creating tables

user2843 Published in June 25, 2018, 7:59 am

I'm following this tutorial: https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro


public class TournamentDbContext : DbContext
    public TournamentDbContext(DbContextOptions<TournamentDbContext> options) : base(options)

    public DbSet<Tournaments> Tournaments { get; set; }
    public DbSet<TournamentType> TournamentType { get; set; }


  public static void Main(string[] args)
        var host = BuildWebHost(args);

        using (var scope = host.Services.CreateScope())
            var services = scope.ServiceProvider;
                var TournamentDb = services.GetRequiredService<TournamentDbContext>();
            catch (Exception ex)
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogError(ex, "An error occurred while seeding the database.");


Initialize method:

public static void Initialize(TournamentDbContext context)

        if (!context.Tournaments.Any())
            context.TournamentType.Add(new Models.Tournaments.TournamentType { Id = 1, Type = "LAN EVENT" });
            context.Tournaments.Add(new Models.Tournaments.Tournaments { Id = 1, Name = "Dummy lan tournament", TournamentTypeId = 1, DateFrom = DateTime.Now, DateTo = DateTime.MaxValue, SalesOpen = DateTime.Now, SalesClose = DateTime.MaxValue, Active = true, DateCreated = DateTime.Now });

Whenever I run this, exception always gets thrown. "Object reference not set to an instance of an object." With the following stacktrace:

Stacktrace: StackTrace = "   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.System.IObserver<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.OnNext(KeyValuePair`2 keyValuePair)\r\n   at System.Diagnostics.DiagnosticListener

If I run a debugger, it gets past the EnsureCreated() method, but it doesn't create the tables. The exception gets thrown at: !context.Tournaments.Any()

Any ideas how to fix this?

UPDATE: I tried this on my laptop, same problem. I also tried doing the initial migration (add-migration, update-database) and changing context.Database.EnsureCreated() to context.Database.Migrate(). And the error is the same, except the problem occurs are context.SaveChanges()

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.323389 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO