我有这个实体:
public class GWDetail: Entity
{
public int? GWNR { get; set; }
public double? PRNR { get; set; }
public double? GWO { get; set; }
public double? GWU { get; set; }
}
用复合PK映射
// Primary Key
HasKey(t => new { t.PRNR, t.GWNR });
并希望将其更改为:
public class GWDetail: Entity
{
public int? GWNR { get; set; }
public int? PRNR { get; set; } // change from double to int !!
public double? GWO { get; set; }
public double? GWU { get; set; }
}
和
// Primary Key
HasKey(t => t.Id)
我已经创建了add-migration脚本并应用了update-database,但得到了:
错误号码:5074,州:1,班级:16 对象'PK_dbo.GWDetail'依赖于列'PRNR'。 ALTER TABLE ALTER COLUMN PRNR失败,因为一个或多个对象访问此列。
GWDetail还没有任何记录。但是有一个父表通过GWNR与它有1:n的关系。父表有记录。
有人可以帮我吗? 谢谢和问候,Manu
答案 0 :(得分:0)
我通过更改迁移脚本中的操作顺序来自行完成。
这是由EF创建的脚本:
public override void Up()
{
AddColumn("dbo.GWDetails", "Id", c => c.Int(nullable: false, identity: true));
AlterColumn("dbo.GWDetails", "PRNR", c => c.Int(nullable: false));
AlterColumn("dbo.GWDetails", "GWNR1", c => c.Int());
DropPrimaryKey("dbo.GWDetails", new[] { "PRNR", "GWNR1" });
AddPrimaryKey("dbo.GWDetails", "Id");
}
这里是我用来更新数据库的脚本:
public override void Up()
{
DropPrimaryKey("dbo.GWDetails", new[] { "PRNR", "GWNR1" });
AlterColumn("dbo.GWDetails", "PRNR", c => c.Int(nullable: false));
AlterColumn("dbo.GWDetails", "GWNR1", c => c.Int());
AddColumn("dbo.GWDetails", "Id", c => c.Int(nullable: false, identity: true));
AddPrimaryKey("dbo.GWDetails", "Id");
}
关键行动是:
DropPrimaryKey("dbo.GWDetails", new[] { "PRNR", "GWNR1" });
我必须放在脚本的第一行。我不明白为什么EF会尝试创建新密钥,而旧密钥仍然存在。 此致,Manu