簡體   English   中英

在EF上級聯多對多關系上刪除

[英]Delete on cascade many-to-many relationship on EF

這些是我的表:

表

是否有一種標准方法在它們之間應用DELETE ON CASCADE?

在一對多關系中,我沒有問題,但是在這種情況下,我必須使用我編寫的方法手動刪除。

如圖所示,您只有兩個桌子。 不可能將它們之間的關系設置為多對多(僅當您將在出現新對時在此表中添加新列,但這是非常不好的做法)。 您應該創建第三個表,該表將包含成對的主鍵。 並且在遷移時,您將能夠在每個主表與第三個主表之間將cascadeDelete指定為true。 見下文:

楷模:

public class BugReport
{
    public BugReport()
    {
        dublicates = new HashSet<DublicateBugReport>();
    }        

    public int ID { get; set; }
    public virtual ICollection<DublicateBugReport> dublicates { get; set; }
}

public class DublicateBugReport
{
    public DublicateBugReport()
    {
        reports = new HashSet<BugReport>();
    }        

    public int ID { get; set; }
    public virtual ICollection<BugReport> reports { get; set; }
}

遷移的一部分:

    public override void Up()
    {
        CreateTable(
            "BugReports",
            c => new
                {
                    ID = c.Int(nullable: false, identity: true),
                })
            .PrimaryKey(t => t.ID)                ;

        CreateTable(
            "DublicateBugReports",
            c => new
                {
                    ID = c.Int(nullable: false, identity: true),
                })
            .PrimaryKey(t => t.ID)                ;

        CreateTable(
            "DublicateBugReportBugReports",
            c => new
                {
                    DublicateBugReport_ID = c.Int(nullable: false),
                    BugReport_ID = c.Int(nullable: false),
                })
            .PrimaryKey(t => new { t.DublicateBugReport_ID, t.BugReport_ID })                

            //pay attention! - cascadeDelete: true
            .ForeignKey("DublicateBugReports", t => t.DublicateBugReport_ID, cascadeDelete: true)
            .ForeignKey("BugReports", t => t.BugReport_ID, cascadeDelete: true)
            .Index(t => t.DublicateBugReport_ID)
            .Index(t => t.BugReport_ID);

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM