繁体   English   中英

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

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


因此,现在我尝试将Code first方法与几个现有表一起使用。

因此,在此之前,我已有一个带有模型的表:

[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; }
}

并且该实体说明了时间序列元素。 因此,现在我需要添加与此数据具有一对多关系的新实体。 所以我加课

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但是数据库中没有这样的约束,但是有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 问题是-最优雅的方法是什么?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM