Sql EF6中已有表的一对多关系:ALTER table语句与外键约束冲突
所以现在我尝试使用代码优先的方法来处理几个现有的表 因此,在此之前,我有一个模型为的表:Sql EF6中已有表的一对多关系:ALTER table语句与外键约束冲突,sql,.net,sql-server,entity-framework,entity-framework-migrations,Sql,.net,Sql Server,Entity Framework,Entity Framework Migrations,所以现在我尝试使用代码优先的方法来处理几个现有的表 因此,在此之前,我有一个模型为的表: [Table("Existed1")] public class TimeSerieEntity { [Key] [Column(Order = 0)] [StringLength(3)] public string TsId { get; set; } [Key] [Column(Order = 1, TypeName = "date")] pu
[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; }
}
并添加以下映射:
`modelBuilder.Entity<TSRootEntity>()
.HasMany(c => c.Values)
.WithRequired(ts => ts.TSMD)
.WillCascadeOnDelete(false);
请帮我修一下
出于某种原因,它尝试使用
PK\u dbo.Existed1
但在DB中没有这样的约束,但是有PK\u 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
为空。所以它试图将所有外键映射到不存在的主键。这就是让它失败的原因
为了解决这个问题,我们还需要prefillTSRootEntity
。问题是——最优雅的方式是什么
{"'PK_dbo.Existed1' is not a constraint.\r\nCould not drop constraint. See previous errors."}
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'.