我想从autoincrement id转移到复合主键。那么,这两个实体
public class SeasonTeam
{
public int SeasonTeamId { get; set; }
public int SeasonId { get; set; }
public int TeamId { get; set; }
}
public class GroupEntry
{
public int GroupEntryId { get; set; }
public int SeasonTeamId { get; set; }
public SeasonTeam SeasonTeam { get; set; }
}
现在看起来像这样
public class SeasonTeam
{
public int SeasonId { get; set; }
public int TeamId { get; set; }
}
public class GroupEntry
{
public int GroupEntryId { get; set; }
public int SeasonId { get; set; }
public int TeamId { get; set; }
public SeasonTeam SeasonTeam { get; set; }
}
Visual Studio生成了迁移代码,但它破坏了数据。
migrationBuilder.AddColumn<int>(
name: "SeasonId",
table: "GroupEntry",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "TeamId",
table: "GroupEntry",
nullable: false,
defaultValue: 0);
migrationBuilder.DropForeignKey(name: "FK_GroupEntry_SeasonTeam_SeasonTeamId", table: "GroupEntry");
migrationBuilder.DropPrimaryKey(name: "PK_SeasonTeam", table: "SeasonTeam");
migrationBuilder.DropColumn(name: "SeasonTeamId", table: "SeasonTeam");
默认值0显然不会起作用,我需要参考的SeasonTeam表中的ID,但我没有找到任何示例。在删除旧的主键列之前,如何为新的复合键设置正确的id值?
答案 0 :(得分:1)
您无法使用EF的API以编程方式执行此操作,但是,如果您可以编写SQL以将值从一个表移动到另一个表,则可以在添加列操作之后和删除列操作之前添加自定义迁移步骤
migrationBuilder.Sql(@"INSERT INTO ...(your SQL here)");
根据您问题中的有限信息,我无法告诉您SQL应该是什么。