How to configure a cascade delete to an Code First Project without setting the navigation properties to [Required] or non nullable ?
for instance:
class MainClass{
[Key] int id {get;set;}
public string name {get;set;}
public virtual ICollection<SubItem> subItems {get;set}
}
and
Class SubItem{
[Key] int id {get; set;}
public string name {get;set;}
}
Deleting the main class should delete all related SubItems
To have cascade deletes on Nullable foreign keys through a code first set up, the best way to achieve this is probably through the Fluent API.
Add this Fluent API code to your DBContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SubItem>()
.HasOptional(o => o.MainClass)
.WithMany(m => m.subItems)
.HasForeignKey(k => k.MainClassId)
.WillCascadeOnDelete(true);
}
and your SubItem class needs to be updated with these properties:
Class SubItem
{
[Key] int id {get; set;}
public string name {get;set;}
public int? MainClassId { get; set;}
public virtual MainClass MainClass { get; set; }
}
I believe if you are deleting the MainClass item the SubItems MUST be loaded in the context (using an include statement when pulling the MainClass object) to be deleted.
but if you go into your database and set up this foreign key to have cascade on delete enabled, then you will not have to have the SubItems loaded into the context because the database will take care of the cascade deleting for you when the MainClass object is deleted.