Home > Software design >  ASP.NET Core 7.0 : seeding data in DBContext
ASP.NET Core 7.0 : seeding data in DBContext

Time:12-01

What should I do?

public class RoleTable : UserBaseEntities
{
    public String RoleName { get; set; } = "";

    public ICollection<UserInRoleTable> UserInRoleTables { get; set; } = new HashSet<UserInRoleTable>();
}

private void SeedData(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<RoleTable>().HasData(new RoleTable { Id = 1, RoleName = nameof(UserRole.Admin) });
    modelBuilder.Entity<RoleTable>().HasData(new RoleTable { Id = 2, RoleName = nameof(UserRole.Operator) });
    modelBuilder.Entity<RoleTable>().HasData(new RoleTable { Id = 3, RoleName = nameof(UserRole.Customer) });
    modelBuilder.Entity<RoleTable>().HasData(new RoleTable { Id = 3, RoleName = nameof(UserRole.Warranty) });
}

I get this error:

The seed entity for entity type 'RoleTable' cannot be added because another seed entity with the same key value for {'Id'} has already been added. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

I don't know what and how to do it - I'm trying ...

CodePudding user response:

You've got 2 records with Id = 3. Change one to 4 and try again.

modelBuilder.Entity<RoleTable>().HasData(new RoleTable { Id = 3, RoleName = nameof(UserRole.Customer) });
modelBuilder.Entity<RoleTable>().HasData(new RoleTable { Id = 3, RoleName = nameof(UserRole.Warranty) });
  • Related