简体   繁体   English

实体框架核心运行种子

[英]Entity Framework Core run seed

I use EF Core to create AppDBContext and AppDbContextSeed : 我使用EF Core创建AppDBContextAppDbContextSeed

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. 当我运行add-migrationupdate-database ,没有appDbContextSeed数据插入数据库。 What did I do wrong? 我做错了什么?

You put your seed execution on the Main method wich is run only on application startup. 您可以将种子执行放在Main方法上,而Main方法仅在应用程序启动时运行。 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. 如果希望在执行update-database命令的同时执行种子方法,则需要遵循EF Core 2.1中的数据播种新功能。 That feature adds a new method on entity configuration HasData which let you add some initial data. 该功能为实体配置HasData添加了新方法,可让您添加一些初始数据。

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. 与EF6中不同,在EF Core中,种子数据与实体类型相关联,作为模型配置的一部分。 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. 然后,当将数据库升级到模型的新版本时,EF Core迁移可以自动计算需要应用哪些插入,更新或删除操作。

I recommend you to read the documentation to know to use that new feature. 我建议您阅读文档以了解使用该新功能的知识。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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