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

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

我将 Asp.Net MVC 5 与 Entity Framework 6 结合使用。我有一个这样的表:

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. 修改你的实体类

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

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

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

关于c# - 将项目移动到 Entity Framework 迁移中的项目列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30151037/

相关文章:

c# - 是否将独立于时区的日期/时间添加周、月或年?

c# - ASP.NET 身份工厂模式是否会破坏 EntityFramework DbContext?

asp.net-mvc - 如何扩展 User.Identity 的可用属性

c# - ASP NET MVC 5 从服务器删除文件

c# - 多步算法的设计模式

c# - 从 PDF 文档中删除超链接 (iTextSharp)

c# - 尝试在 C# 中读取 MJPEG header

c# - LINQ 左外部联接 - 对象引用未设置为对象的实例

c# - Entity Framework : Can a DbContext be fully mocked?

c# - 现有项目中的 ASP.net MVC 5 区域无法正常工作