{"record":{"id":"4723e02a9df0abb3","repo":"dotnet/aspnetcore","slug":"there-is-already-a-persisted-object-under-the-same","errorCode":null,"errorMessage":"There is already a persisted object under the same key '{key}'","messagePattern":"There is already a persisted object under the same key '(.+?)'","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"src/Components/Components/src/PersistentComponentState.cs","lineNumber":120,"sourceCode":"    /// <summary>\n    /// Serializes <paramref name=\"instance\"/> as JSON and persists it under the given <paramref name=\"key\"/>.\n    /// </summary>\n    /// <typeparam name=\"TValue\">The <paramref name=\"instance\"/> type.</typeparam>\n    /// <param name=\"key\">The key to use to persist the state.</param>\n    /// <param name=\"instance\">The instance to persist.</param>\n    [RequiresUnreferencedCode(\"JSON serialization and deserialization might require types that cannot be statically analyzed.\")]\n    public void PersistAsJson<[DynamicallyAccessedMembers(JsonSerialized)] TValue>(string key, TValue instance)\n    {\n        ArgumentNullException.ThrowIfNull(key);\n\n        if (!PersistingState)\n        {\n            throw new InvalidOperationException(\"Persisting state is only allowed during an OnPersisting callback.\");\n        }\n\n        if (!_currentState.TryAdd(key, JsonSerializer.SerializeToUtf8Bytes(instance, JsonSerializerOptionsProvider.Options)))\n        {\n            throw new ArgumentException($\"There is already a persisted object under the same key '{key}'\");\n        }\n    }\n\n    [RequiresUnreferencedCode(\"JSON serialization and deserialization might require types that cannot be statically analyzed.\")]\n    internal void PersistAsJson(string key, object instance, [DynamicallyAccessedMembers(JsonSerialized)] Type type)\n    {\n        ArgumentNullException.ThrowIfNull(key);\n\n        if (!PersistingState)\n        {\n            throw new InvalidOperationException(\"Persisting state is only allowed during an OnPersisting callback.\");\n        }\n\n        if (!_currentState.TryAdd(key, JsonSerializer.SerializeToUtf8Bytes(instance, type, JsonSerializerOptionsProvider.Options)))\n        {\n            throw new ArgumentException($\"There is already a persisted object under the same key '{key}'\");\n        }\n    }","sourceCodeStart":102,"sourceCodeEnd":138,"githubUrl":"https://github.com/dotnet/aspnetcore/blob/294cab2f9b2e03af6b953820c7ab497c3c8b7ad9/src/Components/Components/src/PersistentComponentState.cs#L102-L138","documentation":"PersistAsJson throws ArgumentException when _currentState.TryAdd(key, ...) returns false, i.e. a value already exists under the same key. PersistentComponentState does not overwrite, so duplicate keys during one persist cycle are treated as a programming error.","triggerScenarios":"Two components or services persisting under the same key in the same cycle; calling PersistAsJson twice with the same key; key naming collisions across feature modules.","commonSituations":"Generic key names like \"state\" or \"data\" reused across components; multiple instances of the same component persisting; copy-paste of persistence code without unique keys.","solutions":["Use a unique key per component/service (prefix with the component name or a GUID).","Track which keys have been persisted and skip duplicates, or only persist from a single owner.","If overwriting is desired, design your own state bag instead of relying on PersistAsJson."],"exampleFix":"// before\nState.PersistAsJson(\"state\", a);\nState.PersistAsJson(\"state\", b); // duplicate -> throws\n\n// after\nState.PersistAsJson(\"componentA.state\", a);\nState.PersistAsJson(\"componentB.state\", b);","handlingStrategy":"validation","validationCode":"static readonly HashSet<string> _persistedKeys = new();\nvoid PersistUnique(string key, object value)\n{\n    if (!_persistedKeys.Add(key)) return; // or throw/log\n    State.PersistAsJson(key, value);\n}","typeGuard":null,"tryCatchPattern":"try { State.PersistAsJson(key, value); }\ncatch (ArgumentException ex) when (ex.Message.Contains(\"already a persisted object\"))\n{ logger.LogWarning(ex, \"Duplicate persist key {Key}\", key); }","preventionTips":["Namespace keys per component (e.g. \"MyComponent.cart\").","Track persisted keys to avoid collisions.","Designate a single owner for each persisted key."],"tags":["blazor","persistent-state","duplicate-key","validation"],"analyzedSha":"294cab2f9b2e03af6b953820c7ab497c3c8b7ad9","analyzedAt":"2026-08-06T20:08:02.189Z","schemaVersion":2},"datasetVersion":"2026-08-06T23:17:07.152Z"}