How to keep previously added data when adding new data using seed in .net core?

53 Views Asked by At

First I have added data using modelBuilder in database. enter image description here and after this I have applied add-migration command and update-database command. Now if I try to add new data of Id-6, then it is deleting previously added data(id-1 to 5) from the database. enter image description here My question is I want to keep data from Id 1 to 5 in the database and when I again apply migration I want data with Id 1 to 6.

Now if I try to add new data of Id-6, then it is deleting previously added data(id-1 to 5) from the database. enter image description here My question is I want to keep data from Id 1 to 5 in the database and when I again apply migration I want data with Id 1 to 6.

1

There are 1 best solutions below

0
Wijitha On

Not sure this is the correct way of doing this. Instead of seeding data in DbContext itself, create separate code-first migrations to seed data.

step 01: (Create an empty migration) add-migrations SeedData_Departments_First_Batch

step 02: Use the up() down() methods to insert data and delete them on the rollback.

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.InsertData("TableName",
        new string[] { "Id", "Name", "Age" },
        new object[,]
        {
             { Guid.NewGuid().ToString(), "John", 20 },
             { Guid.NewGuid().ToString(), "Alex", 12 }
        }
    
protected override void Down(MigrationBuilder migrationBuilder)
{
    migrationBuilder.DeleteData("TableName", "Name", new string[] { "John", "Alex" });
}