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

entity-framework entity-framework-core

Question

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

1
2
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().

4
9/1/2017 4:03:01 PM


Related Questions





Related

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