79784405

Date: 2025-10-07 09:48:24
Score: 0.5
Natty:
Report link
public class MyAppContext : DbContext
{
    public MyAppContext(DbContextOptions<MyAppContext> options) : base(options) { }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Item>().HasData(
            new Item { Id = 4, Name = "microphone", Price = 40, SerialNumberId = 10 }
        );

        modelBuilder.Entity<SerialNumber>().HasData(
            new SerialNumber { Id = 10, Name = "MIC150", ItemId = 4 }
        );

        modelBuilder.Entity<Category>().HasData(
            new Category { Id = 1, Name = "Electronics" },
            new Category { Id = 2, Name = "Books" } //Changed Id to 2 (previously duplicated)
        );

        base.OnModelCreating(modelBuilder);
    }

    public DbSet<Item> Items { get; set; }
    public DbSet<SerialNumber> SerialNumbers { get; set; }
    public DbSet<Category> Categories { get; set; }
}

the main issue was that both Category entities had the same Id value.

keep in mind that if your database already contains records with the same primary key values (1 or 2), you’ll still get the same error.

The safest and most common solution is to make the Id field auto-increment (identity) and let the database generate it automatically instead of hardcoding it in the seed data

Reasons:
  • Whitelisted phrase (-1): solution is
  • Long answer (-1):
  • Has code block (-0.5):
  • Me too answer (2.5): get the same error
  • Low reputation (0.5):
Posted by: Alparslan ŞEN