Entity Framework Code First One to One With Cascade Delete

I recently had to figure how to achieve cascade deletes on a one to one mapping. The solution, I soon found out, required fluent configuration.

Here’s some simple entities:

   1: public class Principal
   2: {
   3:     public Int32 PrincipalId { get; set; }
   4:     public virtual Detail Detail { get; set; }
   5:     //other properties go here
   6: }
   7:  
   8: public class Detail
   9: {
  10:     [Key]
  11:     [ForeignKey("Principal")]
  12:     public Int32 PrincipalId { get; set; }
  13:     [Required]
  14:     public Principal Principal { get; set; }
  15:     //other properties go here
  16: }

The fluent configuration needs to be:

   1: protected override void OnModelCreating(DbModelBuilder modelBuilder)
   2: {
   3:     modelBuilder.Entity<Principal>().HasOptional(x => x.Detail).WithRequired(x => x.Principal).WillCascadeOnDelete(true);
   4:  
   5:     base.OnModelCreating(modelBuilder);
   6: }

And that’s it!

In a nutshell:

  • Principal has an optional Detail, lazy loaded;
  • Detail has a required Principal and it gets its primary key from it;
  • When deleting a Principal instance, EFCF will also delete the Detail.

                             

No Comments