Skip to content

Allow delete orphans behavior to be configured differently than cascade delete behavior #10066

@ajbeaven

Description

@ajbeaven

I have the following relationship set up between parent and child entities:

entity.HasOne(d => d.ParentEntity)
    .WithMany(p => p.ChildEntity)
    .HasForeignKey(d => d.IdParentEntity)
    .OnDelete(DeleteBehavior.Restrict)
    .HasConstraintName("FK_Name");

The DeleteBehavior specified here is for the express purpose of avoiding cyclic cascades. In practice, when I sever the relationship between these two entities, I want to delete the EntityChild.

I was a bit surprised to receive the following error when I ran the code parentEntity.Children.Remove(child):

The association between entity types 'ParentEntity' and 'ChildEntity' has been severed but the foreign key for this relationship cannot be set to null. If the dependent entity should be deleted, then setup the relationship to use cascade deletes.

My understanding of the OnDelete action is that it specifies the action to take when ParentEntity is deleted. ParentEntity is not being deleted in the case above, so I question why the OnDelete action has any bearing as to what occurs here.

I'd like to be able to avoid cyclic cascades and still be able to delete ChildEntities via EntityCollection.Remove(TEntity). One alternative is to use ObjectContext.DeleteObject(TEntity) however the ChildEntity removal is occurring in a ParentEntity method (I'm encapsulating the child collection) where there should be no reference to the ObjectContext.

I think it makes sense that if the foreign key for the relationship cannot be set to null that deletion occurs irrespective of the relationship's OnDelete behavior. Perhaps the current behavior is typical of how ORMs handle this sort of thing, but I figured I'd log this just in case.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions