如何在实体框架中创建将一对关系更改为一对多的迁移?



我有表ClothesCollections。原来每个Clothes只能在一个集合中:

public class Clothes
{
public int Id { get; set; }
public int CollectionId { get; set; }
public int Collection { get; set; }
}
public class Collection
{
public int Id { get; set; }
}

然而,现在我需要改变它,所以每个Clothes可以在几个Collections。逻辑中的更改很简单:

public class Clothes
{
public int Id { get; set; }
public ICollection<ClothesCollection> ClothesCollections { get; set; }
}
public class ClothesCollectionDbModel
{
public int ClothesId { get; set; }
public Clothes Clothes { get; set; }
public int CollectionId { get; set; }
public Collection Collection { get; set; }
}
public class CollectionDbModel
{
public int Id { get; set; }
public ICollection<ClothesCollection> ClothesCollections { get; set; }
}

问题在于数据迁移。我想保存所有现有的CollectionId的衣服,并将它们移动到一个新的表ClothesCollection。我假设我需要在新的Migration中使用

执行此操作
protected override void Up(MigrationBuilder migrationBuilder)
{
var data = migrationBuilder.Sql(@"SELECT ""Id"", ""CollectionId""FROM ""Clothes""");
}

但是我不知道如何将SQL查询结果加载到内存中,然后使用它来填充新表。我错过什么了吗?

刚刚发布问题后,我意识到我不需要将数据加载到内存中。我可以解决这个问题的方法是编写以下代码:

migrationBuilder.Sql("INSERT INTO "ClothesCollections" ("ClothesId", "CollectionId") SELECT "Id", "CollectionId" FROM "Clothes"");

问题是我需要改变这里迁移过程的顺序。默认情况下,EF删除现有的列和索引,然后创建一个新表。我不得不按以下方式重新排序:

  1. 创建ClothesCollection表、索引和外键
  2. 运行复制数据的SQL脚本
  3. 删除旧索引,外键,列