{"record":{"id":"8f1b580cf7ff9d1d","repo":"sschmid/Entitas","slug":"entity-for-key-key-already-exists","errorCode":null,"errorMessage":"Entity for key '{key}' already exists!","messagePattern":"Entity for key '(.+?)' already exists!","errorType":"exception","errorClass":"EntityIndexException","httpStatus":null,"severity":"error","filePath":"src/Entitas/EntityIndex/PrimaryEntityIndex.cs","lineNumber":69,"sourceCode":"            {\n                if (entity.Aerc is SafeAERC safeAerc)\n                {\n                    if (safeAerc.Owners.Contains(this))\n                        entity.Release(this);\n                }\n                else\n                {\n                    entity.Release(this);\n                }\n            }\n\n            _index.Clear();\n        }\n\n        protected override void AddEntity(TKey key, TEntity entity)\n        {\n            if (_index.ContainsKey(key))\n                throw new EntityIndexException(\n                    $\"Entity for key '{key}' already exists!\",\n                    \"Only one entity for a primary key is allowed.\");\n\n            _index.Add(key, entity);\n\n            if (entity.Aerc is SafeAERC safeAerc)\n            {\n                if (!safeAerc.Owners.Contains(this))\n                    entity.Retain(this);\n            }\n            else\n            {\n                entity.Retain(this);\n            }\n        }\n\n        protected override void RemoveEntity(TKey key, TEntity entity)\n        {","sourceCodeStart":51,"sourceCodeEnd":87,"githubUrl":"https://github.com/sschmid/Entitas/blob/37547d1bd280f3f1c1ef7edb44f2a206660fbfb4/src/Entitas/EntityIndex/PrimaryEntityIndex.cs#L51-L87","documentation":"Thrown by PrimaryEntityIndex.AddEntity when an entity already exists in the index for the given key. A primary entity index enforces a strict one-entity-per-key invariant (e.g. username -> entity), unlike a normal EntityIndex which supports multiple entities per key.","triggerScenarios":"Creating a second entity whose key component (e.g. a primary key like Username or Id) resolves to a key that is already indexed; calling index.AddEntity manually for an existing key.","commonSituations":"Spawning two players with the same name/id; loading saved data twice so a duplicate key entity is created; resetting entities without clearing the index; code-generated key getters returning a constant for malformed components.","solutions":["Ensure the key is unique before creating the entity — check via index.TryGetEntity(key, out var e)","Use context.DestroyEntity(existing) before creating a new entity for the same key","Use a non-primary EntityIndex if multiple entities per key are actually allowed","Fix key-component generation so it cannot produce duplicates (e.g. auto-increment ids)"],"exampleFix":"// before\nvar e = context.CreateEntity();\ne.AddUserName(requestedName); // throws if name already indexed\n// after\nif (!_index.TryGetEntity(requestedName, out var existing)) {\n    var e = context.CreateEntity();\n    e.AddUserName(requestedName);\n} else {\n    existing.ReplaceUserName(requestedName); // reuse or reject\n}","handlingStrategy":"validation","validationCode":"if (!primaryIndex.TryGetEntity(key, out var existing)) { /* safe to add */ }","typeGuard":"bool KeyIsFree(PrimaryEntityIndex<Entity, string> idx, string key) => !idx.TryGetEntity(key, out _);","tryCatchPattern":"try { index.AddEntity(key, entity); }\ncatch (EntityIndexException ex) { Debug.LogWarning($\"duplicate primary key '{key}': {ex.Message}\"); }","preventionTips":["Check the index (TryGetEntity) before creating an entity with a key","Destroy or reuse the existing entity for the key instead of adding a second one","Guarantee key uniqueness at the source (ids, name validation)","Use a regular EntityIndex when multiple entities per key are intended"],"tags":["csharp","entitas","entity-index","duplicate-key"],"backgroundTag":"file-already-exists","analyzedSha":"37547d1bd280f3f1c1ef7edb44f2a206660fbfb4","analyzedAt":"2026-09-14T00:26:23.246Z","contentChangedAt":"2026-09-14T00:26:23.246Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}