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

Database.EnsureCreated() not creating tables

Ashley
1#
Ashley Published in 2018-01-12 21:44:28Z

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

TournamentDbContext.cs:

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

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

Program.cs

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

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

        host.Run();
    }

Initialize method:

public static void Initialize(TournamentDbContext context)
    {
        context.Database.EnsureCreated();

        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 });
            context.SaveChanges();
        }
    }

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()

Ashley
2#
Ashley Reply to 2018-01-15 16:39:01Z

Basically, I have no idea what happens in that tutorial, or why that solution works.

I found out that services aren't built in program.cs yet, that's why the code won't work. A workaround that I'm using is this

    public static void Seed(IServiceCollection services)
    {
        ServiceProvider serviceProvider = services.BuildServiceProvider();
        var TournamentDb = serviceProvider.GetRequiredService<TournamentDbContext>();
        DbInitializer.Initialize(TournamentDb);
    }

Inside Startup.cs, and I call in inside public void ConfigureServices(IServiceCollection services) using Startup.Seed(services).

I don't know if this is how it's meant to be used, but it does work.

You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO