【问题标题】:Entity Framework Core Re-Seed data实体框架核心重新播种数据
【发布时间】:2020-08-07 16:21:26
【问题描述】:
  • EF Core 版本 3.1.4。
  • SQL Server 2014。

从数据库中删除数据后,如何让 EF 核心重新播种数据?它直接在数据库中删除,而不是通过 EF 核心迁移。

我最新的迁移文件有这个:

migrationBuilder.InsertData(
            table: "Person",
            columns: new[] { "ID", "Name" },
            values: new object[]
            {
                { 1, "Tom Watson" }
            });

在运行Update-Database 后,ID 为 1 的人被创建,然后有人在 SQL Server 中运行delete from Person。此时我想重新播种数据。运行 Update-Database 不会将 Person 插入回数据库中。

我当前的解决方案是删除我的modelBuilder.Entity<Person>().HasData(...) 代码,创建一个新的迁移,然后重新添加该代码并创建另一个迁移,最后是Update-Database。这是一个丑陋的解决方案,会产生不需要的迁移。

有什么想法吗?显然,我可以在数据库上进行插入操作,但我想通过 EF 包管理器控制台来执行此操作,因为我有比这一条记录更多的种子数据。

【问题讨论】:

    标签: entity-framework entity-framework-core


    【解决方案1】:

    根据Microsoft documentation,您可以像这样使用种子数据。

    在这种情况下InitializePersons每次运行程序都会检查,如果数据库中没有记录,则再次在数据库中保存一条新记录。

    public static void Main(string[] args)
    {
         var host = CreateWebHostBuilder(args).Build();
    
        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            try
            {
                var context = services.GetRequiredService<DbContext>();
                DbInitializer.InitializePersons(context);
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogError(ex, "An error occurred while seeding the database.");
            }
        }
    
        host.Run();
    }
    
    public static class DbInitializer
    {
        public static void InitializePersons(DbContext context)
        {
            context.Database.EnsureCreated();
            context.Persons.Add(new Person() { Id = 1, Name = "Tom Watson" });
            context.SaveChanges();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-19
      • 2018-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-30
      • 2020-07-19
      • 1970-01-01
      相关资源
      最近更新 更多