Issue when perform delete cascade

Jan 7 at 1:32 PM
Edited Jan 7 at 3:07 PM

I have very strange situation to resolve.
When I delete object by ID - every think works but
when I load subitem to Document (means DocumentPosition) and remove Document then I got .NET exception

I have Hierarchy
  • Document
    • DocumentPosition
      • DocumentResource
        • DocumentPackage
All are mapped with relation
        HasRequired(t => t.Document)
            .WithMany(t => t.DocumentPositions)
            .HasForeignKey(t => t.DocumentId);
public class Document : Entity
        public Document()
            DocumentPositions = new List<DocumentPosition>();

        public int DocumentId { get; set; }
        public virtual ICollection<DocumentPosition> DocumentPositions { get; set; }
public class DocumentPosition : Entity
        public DocumentPosition()
            DocumentResources = new List<DocumentResource>();

        public int DocumentPositionId { get; set; }
        public int DocumentId { get; set; }
        public virtual Document Document { get; set; }
        private void SyncObjectsStatePreCommit()
            foreach (var dbEntityEntry in ChangeTracker.Entries())
                ** dbEntityEntry.State = StateHelper.ConvertState(((IObjectState)dbEntityEntry.Entity).ObjectState);
on entity DocumentPosition (is currently marked as Modified, we override with Unmodified and it cause .NET exception
"The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.",
In addition. The DocumentPosition is in _entityWpithConceptualNulls visible and in _modifiedEntityStore too.



dbEntityEntry.State equals Modified

dbEntityEntry.Entity).ObjectState) equals Unchanged
Jan 8 at 2:36 PM
Edited Jan 8 at 2:37 PM
Framework don't care about related child with cascade delete.

Solution 1
Delete object first -> We will perform DB cascade delete.
Solution 2
Delete each child loaded to parent, event if we need it to check validation.

In origin EntityFramework it will work with any circumstances.

Topic is related to another: Issue when perform delete cascade