[英]Delete on cascade many-to-many relationship on EF
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.