Removing one child detaches all others in Entity Framework C#

293 views Asked by At

I am trying to understand how cascading delete works. I have mentioned delete cascading to all entities however until I write code to loop through each child. So looping works fine so I am ok with it for now.

The problem I am getting is when I try to delete entity parent having multiple columns with same entity relation.

e.g. I have say working hours entity and then I have 7 columns for Monday to Sunday work hours.

My database looks like Table DayHours DayId OpeningTime ClosingTime

Table WorkingHours WorkingHoursId MonId TueId WedId ThusId FriId SatId SunId

When I delete Workinghours entity I want all dayhours information to be deleted in child table however following code deletes only one entry and others remain orphan as after the first call to RemoveSelfAndChildProperties all others got detached from original parent so it gets child as null and never goes to delete other days...

protected void RemoveSelfAndChildProperties(DatabaseContext context, object parent)
        {
    DbEntityEntry entityEntry = context.Entry(parent);           
    foreach (PropertyInfo property in context.GetNavigationProperties(parent.GetType())){
        object child = property.GetValue(parent);
        if (child != null)
            this.RemoveSelfAndChildProperties(context, child);
        }
    }
    context.Set(parent.GetType()).Remove(entityEntry.Entity);
}
0

There are 0 answers