Entity Framework Core run seed

c# entity-framework-core

Question

I use EF Core to create AppDBContext and AppDbContextSeed:

AppDbContextSeed

public class AppDbContextSeed
{
    private readonly AppDbContext _dbContext;
    private UserManager<AppUser> _userManager;
    private RoleManager<AppRole> _roleManager;

    public AppDbContextSeed(AppDbContext dbContext, UserManager<AppUser> userManager,
        RoleManager<AppRole> roleManager)
    {
        _dbContext = dbContext;
    }

    public async Task Seed()
    {
        ...
        await _dbContext.SaveChangesAsync();
    }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<AppDbContextSeed>();
}

program.cs

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

    using (var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;

        try
        {
            var appDbContextSeed = services.GetService<AppDbContextSeed>();
            appDbContextSeed.Seed().Wait();
        }
        catch (Exception ex)
        {
            var logger = services.GetService<ILogger<Program>>();
            logger.LogError(ex, "An error occurred while seeding the database");
        }
    }

    host.Run();
}

When I run add-migration and update-database, no data from appDbContextSeed is inserted into the database. What did I do wrong?

1
0
7/6/2018 7:40:54 AM

Accepted Answer

You put your seed execution on the Main method wich is run only on application startup. If you want your seed method to be executed at the same time you execute update-database command, you need to follow the new feature of seeding data in EF Core 2.1. That feature adds a new method on entity configuration HasData which let you add some initial data.

This is an excerpt of Data Seeding feature documentation:

Data seeding allows to provide initial data to populate a database. Unlike in EF6, in EF Core, seeding data is associated with an entity type as part of the model configuration. Then EF Core migrations can automatically compute what insert, update or delete operations need to be applied when upgrading the database to a new version of the model.

I recommend you to read the documentation to know to use that new feature.

0
7/6/2018 7:42:20 AM


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