Search code examples
c#entity-framework-coreasp.net-core-identity

Seeding identity data in EF core 6


I'm trying to seed identity roles and users. I have the following:

public class AppDbContext : IdentityDbContext<User, Role, int>
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Role>().HasData(new Role
        {
            Id = 1,
            Name = "SystemAdmin",
            NormalizedName = "SYSTEMADMIN"
        });

        base.OnModelCreating(builder);
    }
}

This creates the role in the DB as expected, however the NormalizedName is left null, regardless of whether I specify a value or not. The same thing happens when trying to create a user with normalized properties.

How do I go about seeding identity data (roles, users) with normalized data in the relevant properties?

Worth noting I'm using:

  • Microsoft.AspNetCore.Identity.EntityFrameworkCore v6.0.8
  • Microsoft.EntityFrameworkCore v6.0.8

Solution

  • This was my mistake... I had created the first migration without specifying the NormalizedName value, then given it a value but not created a new migration to apply this change. So when I ran dotnet ef migrate script, it showed me the script for the first migration, and when I ran dotnet ef database update, it updated the database to apply only the first migration.

    So the obvious fix to this was to create a new migration:

    dotnet ef migrations add NormalizedSeedData
    

    Then update the database with the latest migration:

    dotnet ef database update