{"record":{"id":"6dad1acbee44a855","repo":"dotnet/efcore","slug":"the-entity-of-type-entitytype-is-mapped-as-par","errorCode":null,"errorMessage":"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}'.","messagePattern":"The entity of type '(.+?)' is mapped as part of the document mapped to '(.+?)', but there is no tracked entity of this type with the key value '(.+?)'\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Cosmos/Storage/Internal/CosmosDatabaseWrapper.cs","lineNumber":563,"sourceCode":"                        updateEntry.Entry.Context, errorEntries, (DbUpdateConcurrencyException)exception, null, cancellationToken)\n                    .ConfigureAwait(false)).IsSuppressed\n                    ? throw exception\n                    : false;\n        }\n    }\n\n#pragma warning disable EF1001 // Internal EF Core API usage.\n    // Issue #16707\n    private IUpdateEntry GetRootDocument(InternalEntityEntry entry)\n    {\n        var stateManager = entry.StateManager;\n        var ownership = entry.EntityType.FindOwnership()!;\n        var principal = stateManager.FindPrincipal(entry, ownership);\n        if (principal == null)\n        {\n            if (_sensitiveLoggingEnabled)\n            {\n                throw new InvalidOperationException(\n                    CosmosStrings.OrphanedNestedDocumentSensitive(\n                        entry.EntityType.DisplayName(),\n                        ownership.PrincipalEntityType.DisplayName(),\n                        entry.BuildCurrentValuesString(entry.EntityType.FindPrimaryKey()!.Properties)));\n            }\n\n            throw new InvalidOperationException(\n                CosmosStrings.OrphanedNestedDocument(\n                    entry.EntityType.DisplayName(),\n                    ownership.PrincipalEntityType.DisplayName()));\n        }\n\n        return principal.EntityType.IsDocumentRoot() ? principal : GetRootDocument(principal);\n    }\n#pragma warning restore EF1001 // Internal EF Core API usage.\n\n    private DbUpdateException WrapUpdateException(Exception exception, IReadOnlyList<IUpdateEntry> entries)\n    {","sourceCodeStart":545,"sourceCodeEnd":581,"githubUrl":"https://github.com/dotnet/efcore/blob/dbf9771522148d61a2467854921bd5dc6f6e6916/src/EFCore.Cosmos/Storage/Internal/CosmosDatabaseWrapper.cs#L545-L581","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Ensure the principal (parent) entity is tracked in the same DbContext before saving the owned entity. Add or Attach the parent first.","If the parent was detached, re-attach it: context.Attach(parent) before SaveChanges.","Review cascade delete settings to ensure owned children are removed with their parent.","Avoid using standalone Update/Add on owned entity instances; always operate through the parent."],"exampleFix":"// before\nvar address = new Address { Street = \"Main\", /* ... */ };\ncontext.Entry(address).State = EntityState.Modified; // owned, no parent tracked\nawait context.SaveChangesAsync(); // throws\n\n// after\nvar user = context.Users.Find(userId);\nuser.HomeAddress = address;\nawait context.SaveChangesAsync();","handlingStrategy":"validation","validationCode":"// Before SaveChanges, verify every owned entity has a tracked principal.\nvar orphaned = context.ChangeTracker.Entries()\n    .Where(e => !e.EntityType.IsDocumentRoot() && e.State is EntityState.Added or EntityState.Modified or EntityState.Deleted)\n    .Select(e => (e, ownership: e.EntityType.FindOwnership()))\n    .Where(t => t.ownership is not null && context.Entry(t.e).Context.ChangeTracker.Entries()\n        .All(x => x.Entity != GetPrincipal(t.e, t.ownership!)))\n    .ToList();\nif (orphaned.Count > 0) throw new InvalidOperationException(\"Owned entity has no tracked principal.\");","typeGuard":null,"tryCatchPattern":"// Catch and re-attach the principal, then retry.\ntry { await context.SaveChangesAsync(); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"mapped as part of the document\"))\n{\n    // load/re-attach the parent and retry\n    throw;\n}","preventionTips":["Always add or attach the parent entity before modifying or saving an owned entity.","Avoid detaching parent entities while their owned children are still tracked.","Use ChangeTracker.TrackGraph with care for owned types; verify the full graph is connected."],"tags":["cosmos","owned-entities","change-tracking","savechanges"],"analyzedSha":"dbf9771522148d61a2467854921bd5dc6f6e6916","analyzedAt":"2026-08-06T20:46:03.226Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}