EF Core Seed Migrations: reseeding

c# entity-framework-core sqlite

Question

I am familiar with, and have been using EF Core 2.1 Migrations and seeding. However, I am unclear about how to migrate seeds to a new (changed) version.

So in version 1 of the app I have:

modelBuilder.Entity<Category>().HasData(
  new Category[]
  {
    new Category() { Id = 1, Name = "Category A" },
    new Category() { Id = 2, Name = "Category B" },
    new Category() { Id = 3, Name = "Category C" }
  });

Users have been adding items under these categories, i.e.

public class Category {
    public List<UserItem> Items {get; set;}
}

And FYI: Xamarin Forms - so the database is a Sqlite db on each user's device.

Now I am releasing version 2, and the categories have changed, but I don't want to lose any of the existing user data.

The category seed data now looks like:

modelBuilder.Entity<Category>().HasData(
  new Category[]
    {
      new Category() { Id = 1, Name = "Category A" },
      new Category() { Id = 2, Name = "Category B has a new name" },
      // Category C has been merged with Category B
    });

Category A is unchanged, B has a new name, and C has been removed and C items need to now be under category B.

How is this achieved in EF Core migration to persist the existing UserItems data under the new categories (noting that as each user has their own db I can only migrate using the EF run-time context.Migrate()) ?

1
1
9/5/2018 6:52:06 PM

Accepted Answer

The changes for Category A and Category B should be handled by just adding a new migration after making the changes in your HasData() parameters.

Moving sub-entities from Category C to Category B, however, will require manually editing the migration after it has been added.

0
9/7/2018 1:04:47 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow