I'm getting the below error when adding a migration for postgresql with test data.
The add-migration is working if I specify the Id in the HasData method.
The seed entity for entity type 'Employee' 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.
Employee model
public class Employee
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
In OnModelCreating method
modelBuilder.HasPostgresExtension("uuid-ossp")
.UseIdentityColumns();
modelBuilder.Entity<Employee>(e =>
{
e.Property(p => p.Id).UseIdentityAlwaysColumn();
e.HasData(
new Employee { Name = "Name1" },
new Employee { Name = "Name2" },
new Employee { Name = "Name3" }
);
});
I talked to a friend about this issue and he was able to find out why. Basically, if you use HasData
to insert data on your table, you must provide the key. It's a requirement.
Here's the explanation from microsoft, Data Seeding - Limitations of model seed data
So this answered my question. What I need to do now is to add the Id value specifically.