简体   繁体   English

在EF上级联多对多关系上删除

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

These are my tables: 这些是我的表:

表

Is there a standard way to apply the DELETE ON CASCADE between them ? 是否有一种标准方法在它们之间应用DELETE ON CASCADE?

In one-to-many relationship I had no problem, but in this case I had to manually remove with a method written by me. 在一对多关系中,我没有问题,但是在这种情况下,我必须使用我编写的方法手动删除。

As you showed on the picture you have only two tables. 如图所示,您只有两个桌子。 It is not possible to set relationship between them as many-to-many (only if you will add new columns to this tables when new pairs will appear, but this is very bad practice). 不可能将它们之间的关系设置为多对多(仅当您将在出现新对时在此表中添加新列,但这是非常不好的做法)。 You should create third table, which will contain pairs of their primary keys. 您应该创建第三个表,该表将包含成对的主键。 And at your migration you will be able to specify cascadeDelete to true between each of main tables and this third one. 并且在迁移时,您将能够在每个主表与第三个主表之间将cascadeDelete指定为true。 See below: 见下文:

Models: 楷模:

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; }
}

Piece of Migration: 迁移的一部分:

    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