EF Core 中没有键

问题描述 投票:0回答:1

当我运行

Add-Migration Category
时,我在 ASP.NET Core 5 中收到此错误:

实体类型“User”需要定义主键。如果您打算使用无键实体类型,请在“OnModelCreating”中调用“HasNoKey”。有关无密钥实体类型的更多信息,请参阅 https://go.microsoft.com/fwlink/?linkid=2141943。网站:stackoverflow.com

尽管我的

User
实体确实有主键,但还是会发生此错误:

namespace UCI.Domain.Entities.Users
{
    public class User: BaseEntity
    {
        public long id { get; set; }
        public string FullName { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public bool IsActive { get; set; }
        
        public ICollection<UserInRole> userInRoles { get; set; }
    }
}

这是我的

Role
实体:

namespace UCI.Domain.Entities.Users
{
    public class Role
    {
        public long id { get; set; }
        public string name { get; set; }
        public ICollection<UserInRole> UserInRoles { get; set; }
    }
}

这是我的

UserInRole
实体:

namespace UCI.Domain.Entities.Users
{
    public class UserInRole
    {
        public long id { get; set; }

        // Define the foreign key to associate with the table
        public virtual User User { get; set; }
        public long UserId { get; set; }

        // Define the foreign key to associate with the table
        public virtual Role Role { get; set; }
        public long RoleId { get; set; }
    }
}

这是我的数据库上下文:

namespace UCI.Persistence.Context
{
    public class DataBaseContext : DbContext,IDataBaseContext
    {
        public DataBaseContext(DbContextOptions options):base (options)
        {
        }

        public DbSet<User> Users { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<UserInRole> userInRoles { get; set; }
        public DbSet<Category> Category { get; set; }
  
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>().HasIndex(u => u.Email).IsUnique();

            // modelBuilder.Entity<User>().HasQueryFilter(p => !p.IsRemoved);
            // modelBuilder.Entity<Role>().HasQueryFilter(p => !p.IsRemoved);
            // modelBuilder.Entity<UserInRole>().HasQueryFilter(p => !p.IsRemoved);
            // modelBuilder.Entity<Category>().HasQueryFilter(p => !p.IsRemoved);

            modelBuilder.Entity<Role>().HasData(new Role { id = 1, name = nameof(UserRole.Admin) });
            modelBuilder.Entity<Role>().HasData(new Role { id = 2,  name = nameof(UserRole.Oprator) }); 
            modelBuilder.Entity<Role>().HasData(new Role { id = 3, name = nameof(UserRole.Customer) });
        }
    }
}

如何解决这个错误?

c# sql-server visual-studio entity-framework asp.net-core
1个回答
0
投票

将每个 id 重命名为

Id
或对每个 id 属性使用
[Key]
属性

© www.soinside.com 2019 - 2024. All rights reserved.