与 EF6 中现有 table 的一对多关系:ALTER TABLE 语句与 FOREIGN KEY 约束冲突

One-to-Many relation to existed table in EF6: The ALTER TABLE statement conflicted with the FOREIGN KEY constraint


所以现在我正在尝试将代码优先方法与几个现有的 tables 一起使用。

所以之前我有一个 table 模型:

[Table("Existed1")]
public class TimeSerieEntity 
{
    [Key]
    [Column(Order = 0)]
    [StringLength(3)]
    public string TsId { get; set; }

    [Key]
    [Column(Order = 1, TypeName = "date")]
    public DateTime Date { get; set; }
    public double Value { get; set; }
}

这个实体说明了时间序列元素。所以现在我需要添加与此数据具有一对多关系的新实体。所以我添加 class

public class TSRootEntity 
{
    [Key]
    [StringLength(3)]
    public string Code { get; set; }
    public virtual ICollection<TimeSerieEntity> Values { get; set; }
}

并将 TimeSerieEntity 更改为这个:

   [Table("Existed1")]
   public class TimeSerieEntity  
    {
        [Key, ForeignKey("TSMD")]
        [Column(Order = 0)]
        [StringLength(3)]
        public string TsId { get; set; }

        [Key]
        [Column(Order = 1, TypeName = "date")]
        public DateTime Date { get; set; }

        public double Value { get; set; }

        public virtual TSRootEntity TSMD { get; set; }
}

并添加以下映射:

`modelBuilder.Entity<TSRootEntity>()
                .HasMany(c => c.Values)
                .WithRequired(ts => ts.TSMD)
                .WillCascadeOnDelete(false);

但是当我尝试 运行 迁移时失败并出现错误:

{"'PK_dbo.Existed1' is not a constraint.\r\nCould not drop constraint. See previous errors."}

请帮我解决这个问题。


出于某种原因,它尝试使用 PK_dbo.Existed1 但是在 DB 中没有这样的约束,但是有 PK_Existed1 为什么 EF 添加这个 dbo 前缀?


UPD2:

我通过重命名 PK 约束解决了第一个问题。但现在我有不同的例外:

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Existed1_dbo.TSRootEntity_TsId". The conflict occurred in database "testdb", table "dbo.TSRootEntity", column 'Code'.

好的。发现了问题。所以最后一个错误是因为 Existed1 已经有数据,而 TSRootEntity 是空的。所以它尝试将实际外键映射到不存在的主键。这就是它失败的原因。

因此,为了解决这个问题,我们还需要预填充 TSRootEntity。问题是 - 最优雅的方法是什么?