2

I have a simple DbContext, MyDbContext, with 2 DbSets:

public DbSet<User> Users { get; set; }
public DbSet<Privilege> Privileges { get; set; }

When I ran add-migration in PM console, migrations were generated successfully. I then added code to seed the Privileges table. The code I added is in Startup.Configure():

using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
    serviceScope.ServiceProvider.GetService<OneSourceDbContext>().Database.Migrate();
    serviceScope.ServiceProvider.GetService<OneSourceDbContext>().EnsureSeedData();
}

EnsureSeedData is an extension method that looks like this:

public static void EnsureSeedData(this OneSourceDbContext context)
{
    if (!context.Database.GetPendingMigrations().Any())
    {
        if (!context.Privileges.Any())
        {
                context.Privileges.Add(new Models.Privilege { Name = "Add/Edit" });
                context.SaveChanges();
            }
        }
    }

After adding this code, I deleted all migrations and tried generating again but this time it was saying that Privileges is invalid object. Also, an empty DB was generated even though I have not run the project yet and haven't called update-database. If I comment out EnsureSeedData in Configure() method, migrations get generated.

I thought the 2 lines Database.Migrate() and EnsureSeedData() would only get called when I run the project but it seems that this check inside EnsureSeedData()

!context.Privileges.Any()

is causing migrations to fail. Does add migration really call Configure() in Startup? Its confusing because I only want to create the migration files, why does it run (or seem to run) EnsureSeedData()?

g_b
  • 11,728
  • 9
  • 43
  • 80

1 Answers1

4

Startup.Configure() should only contain code to configure the request pipeline. Any app startup/initialization code should go in Program.Main().

bricelam
  • 28,825
  • 9
  • 92
  • 117
  • Ok, but my question is why does it get called when I run add-migration? Does all code in Startup.Configure() get ran when you call add-migration command? – g_b Sep 02 '17 at 00:57
  • 2
    If `Program.BuildWebHost()` is present, the EF Core Tools will call it to access the application service provider. Yes, this (unfortunately) will call `Startup.Configure()` as a side effect. The The workaround is to remove it and use `IDesignTimeDbContextFactory`. – bricelam Sep 05 '17 at 15:05
  • With the new versions you can even have an async `Main`, and implement it like [this](https://stackoverflow.com/a/61166934/75500). – Shimmy Weitzhandler Apr 12 '20 at 04:38