简体   繁体   中英

Entity Framework Core run seed

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM