简体   繁体   English

实体框架核心重新播种数据

[英]Entity Framework Core Re-Seed data

  • EF Core Version 3.1.4. EF 核心版本 3.1.4。
  • SQL Server 2014. SQL 服务器 2014。

How do I get EF core to re-seed data after it has been deleted out of the database?从数据库中删除数据后,如何让 EF 核心重新播种数据? It's deleted directly in the database, not through an EF core migration.它直接在数据库中删除,而不是通过 EF 核心迁移。

My latest migration file has this:我最新的迁移文件有这个:

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

After running Update-Database the Person with ID 1 is created, then someone runs delete from Person in SQL Server.运行Update-Database后,创建 ID 为 1 的人员,然后有人在 SQL 服务器中运行delete from Person At this point I want to re-seed the data.此时我想重新播种数据。 Running Update-Database does not insert the Person back into the database.运行Update-Database不会将 Person 重新插入数据库。

My current solution is to remove my modelBuilder.Entity<Person>().HasData(...) code, create a new migration, then add that code back in and create another migration and then finally Update-Database .我当前的解决方案是删除我的modelBuilder.Entity<Person>().HasData(...)代码,创建一个新的迁移,然后重新添加该代码并创建另一个迁移,最后Update-Database This is an ugly solution that creates unwanted migrations.这是一个丑陋的解决方案,会产生不需要的迁移。

Any ideas?有任何想法吗? Obviously I can just do an insert on the database, but I'd like to do this through the EF package manager console, as I have a lot more seed data than just this one record.显然,我可以在数据库上进行插入操作,但我想通过 EF package 管理器控制台来执行此操作,因为我有比这一条记录更多的种子数据。

According to Microsoft documentation you can use seed data like this.根据Microsoft 文档,您可以像这样使用种子数据。

In this case InitializePersons is checked every time your program is run, and if there is no record in the database, a new record is saved in the database again.在这种情况下,每次运行程序时都会检查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();
    }
}

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

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