为什么我必须在Entity Framework中关闭级联删除?

时间:2016-05-20 12:26:44

标签: asp.net-mvc database entity-framework

我这里有两个型号:

public class Student
{
    [Key]
    public Guid Id { get; set; }

    public ApplicationUser User { get; set; }

    [Display(Name = "Name"), Required]
    public string Name { get; set; }

    public ICollection<Assessment> SentAssessment { get; set; }

    public ICollection<Assessment> ReceivedAssessment { get; set; }
}

public class Assessment
{
    [Key]
    public Guid Id { get; set; }

    public Student Source { get; set; }

    public Student Target { get; set; }

    [Display(Name = "Assessment Content")]
    public string Content { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Assessment>()
        .HasRequired(eval => eval.Source)
        .WithMany(stu => stu.SentAssessment)
        .Map(conf => conf.MapKey("SourceId"))
        .WillCascadeOnDelete();

    modelBuilder.Entity<Assessment>()
        .HasRequired(eval => eval.Target)
        .WithMany(stu => stu.ReceivedAssessment)
        .Map(conf => conf.MapKey("TargetId"))
        .WillCascadeOnDelete();
}

在此设计中,用户(学生)可以对其他人进行评估。他或她可以看到他/她给予他人的评估和从他人那里得到的评估。

删除学生时,应删除他/她发送或接收的所有评估。所以我编写了WillCascadeOnDelete语句,但是我收到了一个错误:

  

在表'Evaluations'上引入FOREIGN KEY约束'FK_dbo.Evaluations_dbo.Students_TargetId'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。

这里的“周期或多个级联路径”在哪里?

1 个答案:

答案 0 :(得分:0)

这是因为在Student数据库中发生级联删除时,不知道它应该删除Assessment的顺序。您必须手动告诉数据库如何执行此操作:

create trigger T_Student_D
on Student
instead of delete
as
    set nocount on
    delete from Assessment
    where TargetId in (select ID from deleted) or
    SourceId in (select ID from deleted)

    delete from Student where ID in (select ID from deleted)

多个外键是指同一实体的常见问题。