Skip to content

Conversation

Copilot
Copy link
Contributor

@Copilot Copilot AI commented Sep 12, 2025

When moving a child entity between parents with a required relationship configured with DeleteBehavior.NoAction, EF Core incorrectly throws an InvalidOperationException during change tracking:

modelBuilder.Entity<Parent>()
    .HasMany(p => p.Children)
    .WithOne()
    .IsRequired()
    .OnDelete(DeleteBehavior.NoAction);

// This should work but throws an exception
fromParent.Children.Remove(child);
toParent.Children.Add(child);
await context.SaveChangesAsync(); // InvalidOperationException

Root Cause

The issue occurs in InternalEntryBase.HandleNullForeignKey. When a child is removed from a parent collection, the foreign key properties are set to null, which triggers immediate conceptual null validation if DeleteOrphansTiming.Immediate is configured. This validation doesn't account for the fact that the child might be added to another parent in the same change tracking cycle.

Solution

Modified HandleNullForeignKey to defer conceptual null validation for DeleteBehavior.NoAction relationships. This allows entity reparenting to complete before validation occurs, while still properly detecting truly orphaned entities at save time.

The fix:

  • Checks if the property belongs to a foreign key with DeleteBehavior.NoAction
  • Skips immediate conceptual null validation during navigation changes for such relationships
  • Maintains normal validation at SaveChanges time for genuinely orphaned entities

Testing

Added comprehensive test coverage including:

  • Child reparenting scenarios (reproduces and fixes the original issue)
  • Orphaned child detection (ensures the fix doesn't break validation)
  • Multiple children reparenting (tests batch operations)

All existing tests continue to pass, ensuring no regressions in related functionality.

Fixes #35949.


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

@Copilot Copilot AI changed the title [WIP] Error when moving a child object between parents Fix error when moving child entities between parents with DeleteBehavior.NoAction Sep 13, 2025
Copilot finished work on behalf of AndriySvyryd September 13, 2025 00:15
@Copilot Copilot AI requested a review from AndriySvyryd September 13, 2025 00:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Error when moving a child object between parents
2 participants