Does EF Core migrations call Startup.Configure() on add-migration

entity-framework entity-framework-core


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

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" });

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


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

9/1/2017 8:17:03 AM

Accepted Answer

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

9/1/2017 4:03:01 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow