public class Newtask
{
[Key]
public int TId { get; set; }
public string Name { get; set; }
public int Estimated_days_of_work { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
public virtual ICollection<Subtask> Subtasks { get; set; }
}
public class Subtask
{
[Key]
public int SId { get; set; }
public string SubName { get; set; }
public int SEstimated_days_of_work { get; set; }
public int NewtaskTId { get; set; }
public virtual Newtask Newtasks { get; set; }
}
public class SubSubtask
{
[Key]
public int SsId { get; set; }
public string SubSubTaskName { get; set; }
public int SsEstimated_days_of_work { get; set; }
public int NewtaskTId { get; set; }
public int SId { get; set; }
public virtual Newtask Newtasks { get; set; }
public virtual Subtask Subtasks { get; set; }
}
现在我有这些类,我想显示它们之间的关系,就像每个任务都有子任务,而子任务也有其子任务,但是当我运行应用程序时,出现了以下错误:
System.Data.SqlClient.SqlException:'在表'SubSubtasks'上引入FOREIGN KEY约束'FK_dbo.SubSubtasks_dbo.Subtasks_SId'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。无法创建约束或索引。请参阅先前的错误。'
如何修改这种关系?
答案 0 :(得分:0)
您的类正在循环依赖,因此当您删除某些实体时,它将因多个错误而中断。如果忽略删除实体,则可以将其添加到dbcontext类的模型构建器中。
protected override void OnModelCreating(ModelBuilder modelbuilder)
{
foreach (var relationship in modelbuilder.Model.GetEntityTypes().SelectMany(e
=> e.GetForeignKeys()))
{
relationship.DeleteBehavior = DeleteBehavior.Restrict;
}
base.OnModelCreating(modelbuilder);
}
尽管正确的解决方案是更改不会循环依赖的业务模型。 如果您没有发现任何问题,可以通过这种方式更改课程:
public class Newtask
{
[Key]
public int TId { get; set; }
public string Name { get; set; }
public int Estimated_days_of_work { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
public virtual ICollection<Subtask> Subtasks { get; set; }
}
public class Subtask
{
[Key]
public int SId { get; set; }
public string SubName { get; set; }
public int SEstimated_days_of_work { get; set; }
public int NewtaskTId { get; set; }
public virtual Newtask Newtasks { get; set; }
public virtual Substask HasSubtask{get;set;}
}
,然后将dbset中的modelbuilder更改为:
modelbuilder.Entity(typeof (Subtask))
.OnDelete(DeleteBehavior.Restrict);