0

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.

Jack Ray
  • 41
  • 3
  • Dont remove the previously added entitys from your code. EF knows (checks by id) that they exist. Add a new `modelBuilder.Entity.HasData(new Department { Id = 6 ...}`. then add a new migration. Also, please provide code as text, not images. Easier to copy, try locally, paste back to an answer. You'll get mor help, if it's easier for the helpers. – nilsK Mar 29 '23 at 11:55
  • Building a Model is part of Migration when you create the mapping between the c# classes and the tables/fields in the database. Migration is only need when the new properties are added to the database, not the values. You should rarely do a migration. – jdweng Mar 29 '23 at 12:03

1 Answers1

0

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" });
}
Wijitha
  • 1,189
  • 2
  • 12
  • 22