{"record":{"id":"b7dc67f3464cf552","repo":"dotnet/efcore","slug":"a-seed-entity-for-entity-type-entitytype-has-t-b7dc67","errorCode":null,"errorMessage":"A seed entity for entity type '{entityType}' has the same key value as another seed entity mapped to the same table '{table}'. Key values should be unique across seed entities. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting values.","messagePattern":"A seed entity for entity type '(.+?)' has the same key value as another seed entity mapped to the same table '(.+?)'\\. Key values should be unique across seed entities\\. Consider using 'DbContextOptionsBuilder\\.EnableSensitiveDataLogging' to see the conflicting values\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Relational/Migrations/Internal/MigrationsModelDiffer.cs","lineNumber":1936,"sourceCode":"                if (!keyFound)\n                {\n                    continue;\n                }\n\n                if (identityMap.FindCommand(key) is { } existingCommand)\n                {\n                    if (!table.IsShared)\n                    {\n                        if (sensitiveLoggingEnabled)\n                        {\n                            throw new InvalidOperationException(\n                                RelationalStrings.DuplicateSeedDataSensitive(\n                                    entityType.DisplayName(),\n                                    BuildValuesString(key),\n                                    table.SchemaQualifiedName));\n                        }\n\n                        throw new InvalidOperationException(\n                            RelationalStrings.DuplicateSeedData(\n                                entityType.DisplayName(),\n                                table.SchemaQualifiedName));\n                    }\n\n                    command = existingCommand;\n                }\n                else\n                {\n                    command = CommandBatchPreparerDependencies.ModificationCommandFactory.CreateNonTrackedModificationCommand(\n                        new NonTrackedModificationCommandParameters(table, sensitiveLoggingEnabled));\n                    command.EntityState = initialState;\n\n                    identityMap.Add(key, command);\n                }\n\n                foreach (var columnMapping in mapping.ColumnMappings)\n                {","sourceCodeStart":1918,"sourceCodeEnd":1954,"githubUrl":"https://github.com/dotnet/efcore/blob/3a2006ef569de08368d59db5e1468aa8f407e4f8/src/EFCore.Relational/Migrations/Internal/MigrationsModelDiffer.cs#L1918-L1954","documentation":"Thrown by MigrationsModelDiffer while diffing the model to build seed-data modification commands. Two seed entities that map to the same (non-shared) table resolve to the same key, so EF cannot decide which row to insert/update. The non-sensitive form deliberately omits the key value so that data is not leaked into logs; enable EnableSensitiveDataLogging to see it.","triggerScenarios":"ModelCreating HasData(...) for one entity type contains two entries whose key properties evaluate equal, or two entity types mapped to the same table seed colliding keys. Reached when 'dotnet ef migrations add' (or any code path that runs the differ) processes the model.","commonSituations":"Copy-pasted seed rows with unchanged Id; integer key constants that collide; TPH inheritance where base and derived entities seed the same discriminator key; seeding regenerated after a key-column rename where old seed values were not updated.","solutions":["Inspect every HasData block for the named entity type and make each key value unique.","Temporarily call optionsBuilder.EnableSensitiveDataLogging() to print the conflicting key value and locate both entries.","If the collision is intentional (merge), remove one of the duplicate seed entries so only one row is produced.","For shared-table mappings confirm you actually intend one row; otherwise split the entities onto different tables."],"exampleFix":"// before\nmodelBuilder.Entity<Customer>()\n    .HasData(\n        new Customer { Id = 1, Name = \"Acme\" },\n        new Customer { Id = 1, Name = \"Globex\" }); // duplicate Id\n\n// after\nmodelBuilder.Entity<Customer>()\n    .HasData(\n        new Customer { Id = 1, Name = \"Acme\" },\n        new Customer { Id = 2, Name = \"Globex\" });","handlingStrategy":"validation","validationCode":"// Before calling HasData, assert key uniqueness per entity type\nstatic void AssertSeedKeysUnique<TEntity>(\n    IEnumerable<TEntity> seed,\n    Func<TEntity, object> keySelector)\n{\n    var dupes = seed.GroupBy(keySelector)\n                    .Where(g => g.Count() > 1)\n                    .ToList();\n    if (dupes.Count > 0)\n        throw new InvalidOperationException(\n            $\"Duplicate seed keys for {typeof(TEntity).Name}: \" +\n            string.Join(\", \", dupes.Select(g => g.Key)));\n}\n\n// usage in OnModelCreating\nAssertSeedKeysUnique(customers, c => c.Id);","typeGuard":"// Narrow anonymous seed rows to a distinct-by-key set before HasData\nstatic T[] DistinctByKey<T, TKey>(IEnumerable<T> src, Func<T, TKey> key)\n    => src.GroupBy(key).Select(g => g.First()).ToArray();","tryCatchPattern":null,"preventionTips":["Centralize seed data in one file per entity and review it during code review.","Add a unit test that loads the model and asserts every HasData set is key-unique.","Run 'dotnet ef migrations add' in CI to surface seed collisions before deploy."],"tags":["migrations","seeding","data-integrity","model-building"],"backgroundTag":null,"analyzedSha":"3a2006ef569de08368d59db5e1468aa8f407e4f8","analyzedAt":"2026-08-11T23:42:04.146Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}