简体   繁体   中英

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

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM