dotnet/efcore · error · InvalidOperationException

The entity of type ' ' is mapped as part of the document…

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

While preparing a SaveChanges operation, the provider walks up the ownership chain to find the root document for a nested owned entity. FindPrincipal returned null, meaning the parent/principal entity that owns this nested document is not tracked. With sensitive-data logging enabled, the key value of the orphaned entity is included to help diagnose it.

Solutions

  1. Ensure the principal/parent entity is tracked (Attach/Add it) before calling SaveChanges.
  2. Fix the code that nulls out or detaches the parent navigation before saving.
  3. If the principal was deleted, also remove or detach the dependent entities to keep the graph consistent.

Example fix

// before
var order = new Order { Id = 1 };
var detail = new OrderDetail { OrderId = 1, ... };
dbContext.Add(detail); // principal 'order' not tracked
await dbContext.SaveChangesAsync();

// after
dbContext.Add(order);
order.Details.Add(detail);
await dbContext.SaveChangesAsync();
Defensive patterns

Strategy: validation

Validate before calling

// Before SaveChangesAsync, ensure every owned dependent has a tracked principal
foreach (var entry in dbContext.ChangeTracker.Entries())
{
    var ownership = entry.Metadata.FindOwnership();
    if (ownership is null) continue;
    var principal = dbContext.ChangeTracker.Entries()
        .FirstOrDefault(e => e.Metadata == ownership.PrincipalEntityType
            && entry.References(ownership.PrincipalToDependent!));
    if (principal is null)
        throw new InvalidOperationException($"{entry.Metadata.DisplayName()} has no tracked principal.");
}

Try / catch

try { await dbContext.SaveChangesAsync(ct); }
catch (InvalidOperationException ex) when (ex.Message.Contains("no tracked entity of this type"))
{
    // Attach/Add the principal, then retry the save.
}

Prevention

When it happens

Trigger: An owned/dependent entity is tracked in the Added/Modified state but its principal entity (the document root or intermediate owner) is not in the ChangeTracker. GetRootDocument at CosmosDatabaseWrapper.cs:563 calls stateManager.FindPrincipal which returns null, and _sensitiveLoggingEnabled is true, so the sensitive overload is thrown.

Common situations: Attaching an owned entity without its parent. Deleting the principal while dependents remain tracked. Bugs in change tracking where a navigation was set to null before SaveChanges. Asymmetric deserialization that loses the parent reference.

Related errors


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

Appendix: 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 3a2006ef56)