0

I have the following entities and relationship designed using code first...

public class Parent
{
    [Key]
    public int Id {get;set;} //PK

    public ICollection<Child1> Children{get;set;} //one to many
}

public class Child1
{
   [Key]
   public int Id { get; set;} //PK

   [ForeignKey("Parent")]
   public int ParentId {get; set;}

   public Parent { get; set;}

   public Child1Child Child1Child{ get; set; } //one to one Naviation
}

public class Child1Child
{
   [Key, ForeignKey("Child1")]
   public int Child1Id { get; set;} //PK & FK

   public Child1 { get; set; } //one to one
}

Now the Question is deleting a Parent, should that not cascade the deletion to Child1 and Child1Child?

In My case entity framework Cascades up to Child1 but not Child1child. Can some shed some light on what is going on here?

Thank you in advance!

type.parse
  • 21
  • 7
  • You have to use fluent api to do this. Check [this](http://stackoverflow.com/questions/17487577/entity-framework-ef-code-first-cascade-delete-for-one-to-zero-or-one-relations) – FortyTwo May 04 '17 at 21:06
  • But isn't cascade delete default behavior? I tried WillCascadeOnDelete(), if that's what you want meant. – type.parse May 04 '17 at 21:14
  • From a db perspective `ON DELETE CASCADE` needs to be defined between every parent and child table. From a model perspective, you can click on each relationship and set `CASCADE` for OnDelete option. With code first approach you need to override `OnModelCreating` and define `WillCascadeOnDelete` for both Parent and Child entities here. So that Parent will cascade delete the Child and the Child will cascade delete Child1Child – FortyTwo May 04 '17 at 21:43

1 Answers1

0

Found the cause for the issue. The Child1Child was not loaded that caused the entity framework unaware of the Child1Child presence. Otherwise entity framework really cascades delete in this scenario. My bad :).

type.parse
  • 21
  • 7