使用Data Annotations:
如果我們要到一對主從表增加級聯刪除,則要在主表中的引用屬性上增加Required關鍵字,如:
public class Destination { public int DestinationId { get; set; } public string Name { get; set; } public string Country { get; set; } public string Description { get; set; } public byte[] Photo { get; set; } public List<Lodging> Lodgings { get; set; } } public class Lodging { public int LodgingId { get; set; } public string Name { get; set; } public string Owner { get; set; } public bool IsResort { get; set; } public decimal MilesFromNearestAirport { get; set; } [Required] public Destination Destination { get; set; } }
可以看到,在生成的數據庫中,外鍵應用了級聯刪除規則
使用Fluent API:
modelBuilder.Entity<Lodging>().HasRequired(l => l.Destination).WithMany(d => d.Lodgings).WillCascadeOnDelete(true);
相對應的,如果要關閉級聯功能則為:
modelBuilder.Entity<Lodging>().HasRequired(l => l.Destination).WithMany(d => d.Lodgings).WillCascadeOnDelete(false);