简体   繁体   中英

Entity Framework Core Re-Seed data

  • EF Core Version 3.1.4.
  • SQL Server 2014.

How do I get EF core to re-seed data after it has been deleted out of the database? It's deleted directly in the database, not through an EF core migration.

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. At this point I want to re-seed the data. Running Update-Database does not insert the Person back into the database.

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 . 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.

According to Microsoft documentation you can use seed data like this.

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.

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

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