将属性移动到实体框架代码优先迁移中的新实体

时间:2014-08-02 09:01:17

标签: c# sql entity-framework ef-code-first ef-migrations

我在我的项目中使用Entity Framework Code First方法。我有数据库迁移问题。

现在我有了实体

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

我已经拥有现有DataBase中的数据。现在我想扩展City属性,就像这样

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

因此,City将成为拥有众多房产的位置。

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; }
}

因此,我需要在事件表中的每一行创建位置表中的行并复制城市。并将事件本地化的外键设置为位置行。但我不知道如何使用Entity Framework Migration移动现有数据。我已阅读很多关于实体框架迁移的帖子,但没有找到这种情况。

这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:1)

你可以分3步完成

  • 添加位置
  • 插入位置
  • Drop City

开始
public class Event
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string City { get; set; }
}
  • 添加位置属性和类
  • 添加位置迁移并更新数据库

    PM> Enable-Migrations

    PM> Add-Migration AddLocationTable

    PM> Update-Database

  • 创建用于插入数据的空迁移

    PM> Add-Migration InsertLocationData

    该类应该有空UpDown方法。 在Up方法中添加以下代码。

    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();
    }
    
  • 再次运行迁移以应用InsertLocationData迁移。

    PM> Update-Database

  • 删除City属性并运行迁移以应用更改。

    PM> Add-Migration DropCityFromEvent

    PM> Update-Database

相关问题