g_b
g_b

Reputation: 12428

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

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

Upvotes: 2

Views: 1071

Answers (1)

bricelam
bricelam

Reputation: 30345

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

Upvotes: 4

Related Questions