The seed entity for entity type 'X' cannot be added because a non-zero value is required for property 'Id'

Problem

"The seed entity for entity type 'Skill' cannot be added because a non-zero value is required for property 'Id.' Consider providing a negative value to avoid collisions with non-seed data."

I got this error when I tried to seed my database table "Skills" with some initial values. The Id property is the primary key column in the database. As it is an identity column, I didn't provide a value for that column. The following is the table structure.

 public class Skill
    {
        public int Id { get; set; }
        public string SkillName { get; set; }
     }

I used the following code to seed the database table.

  protected override void OnModelCreating(ModelBuilder modelBuilder)
        {          
            modelBuilder.Entity<Skill>().HasData(
            new Skill { SkillName = "Communication" },
            new Skill { SkillName = "Decision-Making" },
            new Skill { SkillName = "Flexibility" },
            new Skill { SkillName = "Innovation" },
            new Skill { SkillName = "Integrity" },
            new Skill { SkillName = "Leadership" },
            new Skill { SkillName = "Time Management" },
            new Skill { SkillName = "Negotiation" }
            );
        }

 

Solution

In Entity Framework Core, primary key properties are converted to identity columns if the database provider is SQL Server. But when we try to seed a database table with an identity column, the corresponding property value should be provided, as the migration scripts are generated by Entity Framework without connecting to the database. So the above code should be modified as follows to fix this issue. 

 protected override void OnModelCreating(ModelBuilder modelBuilder)
        {     
            modelBuilder.Entity<Skill>().HasData(
            new Skill {Id=1, SkillName = "Communication" },
            new Skill {Id=2,  SkillName = "Decision-Making" },
            new Skill { Id = 3, SkillName = "Flexibility" },
            new Skill { Id = 4, SkillName = "Innovation" },
            new Skill { Id = 5, SkillName = "Integrity" },
            new Skill { Id = 6, SkillName = "Leadership" },
            new Skill { Id = 7, SkillName = "Time Management" },
            new Skill { Id = 8, SkillName = "Negotiation" }
            );
        }

Search