dotnet/efcore · error · InvalidOperationException

The entity of type '{entityType}' is mapped as part of the d

Error message

The entity of type '{entityType}' is mapped as part of the document mapped to '{missingEntityType}', but there is no tracked entity of this type with the key value '{keyValue}'.

What it means

When saving a non-document-root entity (one embedded inside an owned navigation), EF Core must find the root document's tracked entry to write to. GetRootDocument (CosmosDatabaseWrapper.cs:554-577) walks the ownership chain looking for a tracked principal. If none is found, the nested entity is 'orphaned' — it has no parent document to be serialized into. This variant (line 563) is thrown when EnableSensitiveDataLogging is on, so it includes the actual key value for diagnostics.

Source

Thrown at src/EFCore.Cosmos/Storage/Internal/CosmosDatabaseWrapper.cs:563

                        updateEntry.Entry.Context, errorEntries, (DbUpdateConcurrencyException)exception, null, cancellationToken)
                    .ConfigureAwait(false)).IsSuppressed
                    ? throw exception
                    : false;
        }
    }

#pragma warning disable EF1001 // Internal EF Core API usage.
    // Issue #16707
    private IUpdateEntry GetRootDocument(InternalEntityEntry entry)
    {
        var stateManager = entry.StateManager;
        var ownership = entry.EntityType.FindOwnership()!;
        var principal = stateManager.FindPrincipal(entry, ownership);
        if (principal == null)
        {
            if (_sensitiveLoggingEnabled)
            {
                throw new InvalidOperationException(
                    CosmosStrings.OrphanedNestedDocumentSensitive(
                        entry.EntityType.DisplayName(),
                        ownership.PrincipalEntityType.DisplayName(),
                        entry.BuildCurrentValuesString(entry.EntityType.FindPrimaryKey()!.Properties)));
            }

            throw new InvalidOperationException(
                CosmosStrings.OrphanedNestedDocument(
                    entry.EntityType.DisplayName(),
                    ownership.PrincipalEntityType.DisplayName()));
        }

        return principal.EntityType.IsDocumentRoot() ? principal : GetRootDocument(principal);
    }
#pragma warning restore EF1001 // Internal EF Core API usage.

    private DbUpdateException WrapUpdateException(Exception exception, IReadOnlyList<IUpdateEntry> entries)
    {

View on GitHub (pinned to dbf9771522)

Solutions

  1. Ensure the principal (parent) entity is tracked in the same DbContext before saving the owned entity. Add or Attach the parent first.
  2. If the parent was detached, re-attach it: context.Attach(parent) before SaveChanges.
  3. Review cascade delete settings to ensure owned children are removed with their parent.
  4. Avoid using standalone Update/Add on owned entity instances; always operate through the parent.

Example fix

// before
var address = new Address { Street = "Main", /* ... */ };
context.Entry(address).State = EntityState.Modified; // owned, no parent tracked
await context.SaveChangesAsync(); // throws

// after
var user = context.Users.Find(userId);
user.HomeAddress = address;
await context.SaveChangesAsync();
Defensive patterns

Strategy: validation

Validate before calling

// Before SaveChanges, verify every owned entity has a tracked principal.
var orphaned = context.ChangeTracker.Entries()
    .Where(e => !e.EntityType.IsDocumentRoot() && e.State is EntityState.Added or EntityState.Modified or EntityState.Deleted)
    .Select(e => (e, ownership: e.EntityType.FindOwnership()))
    .Where(t => t.ownership is not null && context.Entry(t.e).Context.ChangeTracker.Entries()
        .All(x => x.Entity != GetPrincipal(t.e, t.ownership!)))
    .ToList();
if (orphaned.Count > 0) throw new InvalidOperationException("Owned entity has no tracked principal.");

Try / catch

// Catch and re-attach the principal, then retry.
try { await context.SaveChangesAsync(); }
catch (InvalidOperationException ex) when (ex.Message.Contains("mapped as part of the document"))
{
    // load/re-attach the parent and retry
    throw;
}

Prevention

When it happens

Trigger: Attaching or adding an owned entity to the change tracker without also tracking its principal (parent) entity. Detaching the parent while the owned child remains tracked/modified. Deleting the parent without cascading to the child. Loading an owned entity detached and then trying to save it standalone.

Common situations: Deserializing an owned entity from JSON and calling Update/Add without the parent. Using ChangeTracker.TrackGraph incorrectly for owned types. Manual entity graph manipulation that breaks the principal-dependent link. Concurrent context instances detaching shared entities.

Related errors


AI-assisted analysis of dotnet/efcore@dbf9771522 (2026-08-06). Data as JSON: /api/errors/6dad1acbee44a855. Report an issue: GitHub.