Visual Studio EF核心中无密钥

c0vxltue  于 2022-11-17  发布在  其他
关注(0)|答案(1)|浏览(209)

当我运行Add-Migrition 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; }

        //تعریف کید خارجی برای ارتباط با جدول یوزر
        public virtual User User { get; set; }
        public long UserId { get; set; }

        //تعریف کلید خارجی برای ارتباط با جدول رول
        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) });
        }
    }
}

如何解决此错误?

uujelgoq

uujelgoq1#

将Each id重命名为Id或对每个id属性使用[Key]属性

相关问题