Search code examples
c#asp.net-coreentity-framework-coreef-code-first

The entity type 'IdentityUserLogin<string>' requires a primary key to be defined when adding index


I get this error when I try to add an index to a column. Any idea why and how I can address this.

This is how I add the index in my AppDbContext file.

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Category>()
                .HasIndex(b => b.CategoryName).IsUnique();
        }

        public DbSet<Category> Categories { get; set; }

This is the model I am trying to add to my index.

public class Category
{
    public int CategoryId { get; set; }

    [Required]
    public string CategoryName { get; set; }

    public string Description { get; set; }

    public List<unitItem> itemList { get; set; }
}

And I the error is being thrown here

            AppDbContext context = applicationBuilder.GetRequiredService<AppDbContext>();
                if (!context.Categories.Any())
            {
                context.Categories.AddRange(Categories.Select(c => c.Value));
            }

when I try to initialize my DB


Solution

  • Call the base class in your OnModelCreating method. IdentityDbContext uses OnModelCreating as well to configure its classes (like IdentityUserLogin<string>):

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Call the base class first:
        base.OnModelCreating(modelBuilder);
    
        modelBuilder.Entity<Category>()
            .HasIndex(b => b.CategoryName).IsUnique();
    }