Move property to new Entity in Entity Framework Co

2020-08-01 11:27发布

问题:

I'm using Entity Framework Code First approach in my project. I have a problem with database migration.

Now I have the entity

public class Event
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string City { get; set; }
}

I have already have data in my existing DataBase. Now I want to extend City property, like this

public class Event
{
    public int Id { get; set; }
    public string Title { get; set; }
    public virtual Location Location { get; set; }
}

so, City become to Location with many properties.

public partial class Location
{
    public int Id { get; set; }
    public string Country { get; set; }
    public string City{ get; set; }
    public string Address { get; set; }
    public string Place { get; set; }
}

So, I need for each row in Events Table create row in Locations Table and copy city. And set foreign key for event localtion to location row.But I don't know how to move existing data using Entity Framework Migration. I have read many post on Entity Framework Migration, but didn't find this case.

What is the best way to do this?

回答1:

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