简体   繁体   中英

Making the values of EF Core column unique

I don't know if I am doing this right but I basically want to the category names unique in this model

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

I tried using an index and added this to my appDbContext

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

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

but when I run I get this error:

The entity type 'IdentityUserLogin' requires a primary key to be defined. If you intended to use a keyless entity type call 'HasNoKey()'.'

Any solution to this would be appreciated.

The error:

The entity type 'IdentityUserLogin' requires a primary key to be defined. If you intended to use a keyless entity type call 'HasNoKey()'.'

says you must add a Primary Key to the class 'IdentityUserLogin' which would be unique throughout the table.

 public class Category
 {
    [Key] // <--- add this
    public int CategoryId { get; set; }

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

    public string Description { get; set; }

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

The [Key] data annotation is within the namespace using System.ComponentModel.DataAnnotations; (Press Ctrl +. to import the namespace or type manually)

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