将项目移动到Entity Framework迁移中的项目列表

时间:2015-05-10 11:49:50

标签: c# entity-framework asp.net-mvc-5

我正在使用带有Entity Framework 6的Asp.Net MVC 5.我有一个这样的表:

public class Recipe
{
    [Required]
    public virtual Food Food { get; set; }

    //...rest
}

现在我想将Food移到食物清单中。像这样:

public class Recipe
{
    public virtual IList<Food> Foods { get; set; }

    //... rest
}

如果我尝试这个并添加迁移,我将丢失与Food ID相关的数据。并且不知道哪种食谱适合哪种食物。

我尝试保留Food并添加如下列表:

public class Recipe
{
    [Required]
    public virtual Food Food { get; set; }

    public virtual IList<Food> Foods { get; set; }

    //... rest
}

但是迁移添加了第二个外键并且无法更新。这是失败的迁移代码:

    public override void Up()
    {
        DropForeignKey("dbo.Recipes", "Food_ID", "dbo.Foods");
        DropIndex("dbo.Recipes", new[] { "Food_ID" });
        AddColumn("dbo.Foods", "Recipe_Id", c => c.Int());
        AddColumn("dbo.Foods", "Recipe_Id1", c => c.Int());
        AlterColumn("dbo.Recipes", "Food_ID", c => c.Int());
        CreateIndex("dbo.Foods", "Recipe_Id");
        CreateIndex("dbo.Foods", "Recipe_Id1");
        CreateIndex("dbo.Recipes", "Food_ID");
        AddForeignKey("dbo.Foods", "Recipe_Id", "dbo.Recipes", "Id");
        AddForeignKey("dbo.Foods", "Recipe_Id1", "dbo.Recipes", "Id");
        AddForeignKey("dbo.Recipes", "Food_ID", "dbo.Foods", "ID");
    }

如何在不丢失表格中的当前数据的情况下将单个Food移至Food列表?

1 个答案:

答案 0 :(得分:4)

创建后,您需要自定义迁移。

  1. 修改您的实体类

    public class Recipe
    {
        public virtual IList<Food> Foods { get; set; }
    
        //... rest
    }
    
  2. 使用Add-Migration来构建迁移

  3. 修改生成的迁移以使用数据填充新列。您需要使用以前相关行的ID填充Recipe_Id中的新Foods列。

    public override void Up()
    {
        DropForeignKey("dbo.Recipes", "Food_ID", "dbo.Foods");
        DropIndex("dbo.Recipes", new[] { "Food_ID" });
        AddColumn("dbo.Foods", "Recipe_Id", c => c.Int());
    
        // Update values from existing data, not sure if the syntax is perfect
        Sql(@"UPDATE dbo.Foods SET Recipe_Id = r.Id
              FROM (SELECT Id, Food_ID FROM dbo.Recipes) AS r
              WHERE Foods.ID = r.Food_ID");
    
        DropColumn("dbo.Recipes", "Food_ID");
        CreateIndex("dbo.Foods", "Recipe_Id");
        AddForeignKey("dbo.Foods", "Recipe_Id", "dbo.Recipes", "Id");
    }