【问题标题】:Making the values of EF Core column unique使 EF Core 列的值唯一
【发布时间】:2020-11-16 23:54:09
【问题描述】:

我不知道我这样做是否正确,但我基本上想要这个模型中唯一的类别名称

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

我尝试使用索引并将其添加到我的 appDbContext

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

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

但是当我运行时我得到这个错误:

实体类型“IdentityUserLogin”需要定义一个主键。如果您打算使用无密钥实体类型调用“HasNoKey()”。

对此的任何解决方案将不胜感激。

【问题讨论】:

标签: c# asp.net entity-framework-core ef-code-first


【解决方案1】:

错误:

实体类型“IdentityUserLogin”需要定义一个主键。如果您打算使用无密钥实体类型调用“HasNoKey()”。

说您必须向“IdentityUserLogin”类添加一个主键,该主键在整个表中都是唯一的。

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

[Key] 数据注解在命名空间内使用 System.ComponentModel.DataAnnotations;(按 Ctrl + . 导入命名空间或手动键入)

【讨论】:

  • @PaulGudu,您需要构建您的项目 > 然后添加迁移以更改数据库架构,最后更新数据库。除非您添加迁移并更新它,否则数据库将无法识别您的更改并将继续给出相同的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-23
  • 2017-01-11
  • 2020-12-27
  • 2022-11-19
  • 2018-09-14
  • 2020-10-12
  • 2021-06-24
相关资源
最近更新 更多