[英]Moving items to list of items in an Entity Framework migration
I'm using Asp.Net MVC 5 with Entity Framework 6. I've got a table like this: 我正在使用带有Entity Framework 6的Asp.Net MVC 5.我有一个这样的表:
public class Recipe
{
[Required]
public virtual Food Food { get; set; }
//...rest
}
Now I want to move the Food
to a list of foods. 现在我想将
Food
转移到Food
清单中。 Like this: 像这样:
public class Recipe
{
public virtual IList<Food> Foods { get; set; }
//... rest
}
If I try this and add a migration, I'll lose the data related to Food
Ids. 如果我尝试这个并添加一个迁移,我将丢失与
Food
Ids相关的数据。 And won't know which recipe is for which food. 并且不知道哪种食谱适合哪种食物。
I tried keeping the Food
and add the list like this: 我试着保留
Food
并添加如下列表:
public class Recipe
{
[Required]
public virtual Food Food { get; set; }
public virtual IList<Food> Foods { get; set; }
//... rest
}
But the migration adds a second foreign key and fails to update. 但是迁移添加了第二个外键并且无法更新。 Here's the migration code that fails:
这是失败的迁移代码:
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");
}
How can I move the single Food
to a list of Food
s without losing the current data in the table? 我如何移动单一
Food
到列表Food
•不用在表丢失当前数据?
You'll need to customize your migration after creating it. 创建后,您需要自定义迁移。
Modify your entity class 修改您的实体类
public class Recipe { public virtual IList<Food> Foods { get; set; } //... rest }
Use Add-Migration
to scaffold the migration 使用
Add-Migration
来构建迁移
Modify the generated migration to fill the new column with data. 修改生成的迁移以使用数据填充新列。 You'll want to fill the new
Recipe_Id
column in Foods
with the IDs of the previously related rows. 您需要使用以前相关行的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"); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.