Move property to new Entity in Entity Framework Code First Migration

随声附和 提交于 2019-12-06 21:19:26

You could do that in 3 steps

  • Add Location
  • Insert Location
  • Drop City

Starting from

public class Event
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string City { get; set; }
}
  • Add Location property and class
  • Add Location migration and update the database

    PM> Enable-Migrations

    PM> Add-Migration AddLocationTable

    PM> Update-Database

  • Create empty migration for inserting the data

    PM> Add-Migration InsertLocationData

    The class should have empty Up and Down method. Add following code in the Up method.

    using (var context = new AppContext())
    {
        var events = context.Set<Event>().ToArray();
        foreach (var ev in events)
        {
            ev.Location = new Location { City = ev.City };
        }
        context.SaveChanges();
    }
    
  • Run the migration again to apply InsertLocationData migration.

    PM> Update-Database

  • Delete City property and run a migration to apply the changes.

    PM> Add-Migration DropCityFromEvent

    PM> Update-Database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!