【问题标题】:EF Cascade delete from two separate tables从两个单独的表中删除 EF Cascade
【发布时间】:2012-03-29 04:03:39
【问题描述】:

我有以下两个实体:

public class Field {
    public int FieldID { get; set; }
    public String Name { get; set; }
    public int LocationID { get; set; }

    public virtual ICollection<FieldPlanning> FieldPlannings { get; set; }
}

public class Timeslot {
    public int TimeslotID { get; set; }
    public DateTime Start { get; set; }
    public int MatchDayID { get; set; }

    public virtual ICollection<FieldPlanning> FieldPlannings { get; set; }
}

现在这两个实体的组合构成了以下实体:

public class FieldPlanning {
    public int FieldPlanningID { get; set; }
    public int TimeslotID { get; set; }
    public int FieldID { get; set; }


    public virtual Timeslot Timeslot { get; set; }
    public virtual Field Field { get; set; }
    public virtual Match Match { get; set; }
}

然后,此实体还将具有 Match 实体的导航属性,但为简洁起见,我将其省略了。

当删除字段或时间段时,我希望它也删除关联的 FieldPlanning 记录。

如果我运行应用程序,我会收到“Timeslot_FieldPlanning 可能导致循环或多个级联路径”的错误。如果我然后像这样编辑模型创建:

        modelBuilder.Entity<Timeslot>()
            .HasMany(ts => ts.FieldPlannings)
            .WithRequired(fp => fp.Timeslot)
            .HasForeignKey(fp => fp.TimeslotID)
            .WillCascadeOnDelete(false);

如果我随后删除了一个字段,则 FieldPlanning 将随之删除,没有问题。如果我尝试删除时间段,我会收到与以前相同的错误。

如何修复它,以便我可以删除字段或时间段中的任何一个,并且对于这两个实体,CascadeOnDelete 都可以为真?

我阅读了 Hans Riesebos 的回答 here,但不知道如何将其应用于我的问题。

编辑: 我的位置实体:

public class Location {
    public int LocationID { get; set; }
    public String Name { get; set; }
    public Address Address { get; set; }
    public int TournamentID { get; set; }

    public virtual Tournament Tournament { get; set; }

    public virtual ICollection<Field> Fields { get; set; }
}

我的匹配实体:

public class Match {
    public int MatchID { get; set; }
    public Boolean Forfeited { get; set; }
    public int TeamAID { get; set; }
    public int TeamBID { get; set; }
    public int FieldPlanningID { get; set; }
   

    public virtual Team TeamA { get; set; }
    public virtual Team TeamB { get; set; }
    public virtual FieldPlanning FieldPlanning { get; set; }

    public virtual ICollection<Official> Officials { get; set; }
}

在尝试时,我专门将导航属性注释为 Match,所以我可以确保它首先在没有 Match 的情况下工作,因为我知道 FieldPlanning 和 Match 之间的关系有问题,因为这是一个 0..1 到0..1 关系。但我不明白这对我当前的问题有什么影响(只要我在 FieldPlanning 中保留 Match 的导航属性)。

【问题讨论】:

  • 问题很可能与您的 Location 和 Match 实体有关。同时显示这些实体和映射。
  • @LadislavMrnka 我现在也添加了这些实体。

标签: entity-framework cascade relationships


【解决方案1】:

再搜索一点后,我发现this 线程正确地指出SQL Server 不允许这样做。我认为问题出在实体框架上,但在尝试在 SSMS 中重新创建表后,我发现它仍然无法正常工作。

解决方案是禁用其中一个级联效果并使用触发器(或代码)首先删除子行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-29
    • 2020-08-09
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    • 1970-01-01
    相关资源
    最近更新 更多