【发布时间】:2017-03-14 08:54:41
【问题描述】:
您好,我有带有 Entity Framework Core 1.0 RTM 和 SQL 服务器的 MVC 6 应用程序,当我尝试生成数据库表时,出现“引入 FOREIGN KEY 约束可能导致循环或多个级联路径”错误。
我的模型类如下:
类别模型:
public class Category
{
public Category()
{
this.VariableSettings = new List<VariableSetting>();
}
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public List<VariableSetting> VariableSettings { get; set; }
public List<Station> Stations { get; set; }
}
车站型号:
public class Station
{
public int StationId { get; set; }
public string StationName { get; set; }
public double? Longitude { get; set; }
public double? Latitude { get; set; }
public List<VariableRecord> VariableRecords { get; set; }
public int CategoryID { get; set; }
public Category Category { get; set; }
}
变量记录模型:
public class VariableRecord
{
[Key]
public int VariableRecordId { get; set; }
public double Value { get; set; }
public DateTime RecordDate { get; set; }
public int StationId { get; set; }
public Station Station { get; set; }
public int VarSettingId{ get; set; }
public virtual VariableSetting VariableSetting { get; set; }
}
变量设置模型:
public class VariableSetting
{
[Key]
public int VarSettingId { get; set; }
public int Sequence { get; set; }
public double? MinimumValue { get; set; }
public double? MaximumValue { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
public int VariableId { get; set; }
public Variable Variable { get; set; }
public List<VariableRecord> VariableRecords { get; set; }
}
变量模型:
public class Variable
{
public int VariableId { get; set; }
public string VariableName { get; set; }
public string Description { get; set; }
public string Unit { get; set; }
public List<VariableSetting> VariableSettings { get; set; }
}
所以,在我的代码 Category->Station->VariableRecord 和 Category->VariableSetting->VariableRecord 中也有级联删除路由,所以我试图在上下文类中禁用路由 Category->VariableSetting->VariableRecord Fluent API 如下:
builder.Entity<VariableRecord>()
.HasOne(pt => pt.VariableSetting)
.WithMany(p => p.VariableRecords)
.HasForeignKey(pt => pt.VarSettingId)
.OnDelete(DeleteBehavior.Cascade);
但是我仍然得到以下相同的结果:
System.Data.SqlClient.SqlException (0x80131904):引入 FOREIGN 表上的 KEY 约束“FK_VariableSetting_Category_CategoryId” 'VariableSetting' 可能会导致循环或多个级联路径。请指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN 关键约束。
我在这些代码上卡了几天,但仍然无处可去,请帮助!
【问题讨论】:
-
只有一件事,我在核心开发时也发现:尝试使用属性 ->
[ForeignKey("")]和[InverseProperty("")]- 这减少了例如那些错误。 docs.efproject.net/en/latest/modeling/… EFs fluent API 不是我的大爱,所以我不能在不混淆你的情况下写一些东西:D -
OnDelete(DeleteBehavior.Cascade)实际上激活了行为,对吗?将DeleteBehavior更改为其他一些值可能是什么?只是一个猜测,还没有使用核心。
标签: c# sql entity-framework asp.net-core-mvc entity-framework-core