【问题标题】:Entity Framework Core run seedEntity Framework Core 运行种子
【发布时间】:2018-07-06 15:42:20
【问题描述】:

我使用 EF Core 创建AppDBContextAppDbContextSeed

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>();
}

程序.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();
}

当我运行add-migrationupdate-database 时,没有来自appDbContextSeed 的数据插入到数据库中。我做错了什么?

【问题讨论】:

  • 看起来不错,但与 update-database 的(预期)关系是什么?这在启动时运行,您需要检查是否每次都需要播种。

标签: c# entity-framework-core


【解决方案1】:

您将种子执行放在Main 方法上,该方法仅在应用程序启动时运行。如果希望在执行update-database 命令的同时执行种子方法,则需要遵循 EF Core 2.1 中的种子数据新功能。该功能在实体配置HasData 上添加了一个新方法,可让您添加一些初始数据。

这是Data Seeding 功能文档的摘录:

数据播种允许提供初始数据来填充数据库。 与 EF6 不同,在 EF Core 中,播种数据与实体相关联 类型作为模型配置的一部分。然后 EF Core 迁移可以 自动计算需要哪些插入、更新或删除操作 将数据库升级到模型的新版本时应用。

我建议您阅读文档以了解如何使用该新功能。

【讨论】:

  • 谢谢你帮了我很多(赞)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-07
  • 1970-01-01
  • 2017-04-26
  • 2019-01-11
  • 2016-09-17
  • 1970-01-01
相关资源
最近更新 更多