简体   繁体   English

ASP.NET 核心 Web API - 实体类型'IdentityUserRole<long> ' 需要定义一个主键</long>

[英]ASP.NET Core Web API - The entity type 'IdentityUserRole<long>' requires a primary key to be defined

I am implementing IdentityDbContext in ASP.NET Core Web API.我在 ASP.NET 核心 Web API 中实现 IdentityDbContext。

IdentityModel:身份模型:

public class ApplicationUser : IdentityUser<long>
{
    public DateTime? LastLogin { get; set; }
    public ICollection<ApplicationUserRole> UserRoles { get; set; }
}

public class ApplicationRole : IdentityRole<long>
{
    public ICollection<ApplicationUserRole> UserRoles { get; set; }
}

public class ApplicationUserRole : IdentityUserRole<long>
{
    public virtual ApplicationUser User { get; set; }
    public virtual ApplicationRole Role { get; set; }
}

AppDbContext:应用数据库上下文:

public class AppDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, long, IdentityUserClaim<long>, ApplicationUserRole, IdentityUserLogin<long>, IdentityRoleClaim<long>, IdentityUserToken<long>>
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }

    public DbSet<ApplicationRole> ApplicationRole { get; set; }
    public DbSet<ApplicationUserRole> ApplicationUserRole { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        this.SeedUsers(builder);
        this.SeedRoles(builder);
        this.SeedUserRoles(builder);

        builder.Entity<ApplicationUser>(entity =>
        {
            entity.Property(u => u.Id).ValueGeneratedOnAdd();
            entity.HasIndex(u => u.Email).IsUnique();
        });
        builder.Entity<ApplicationRole>(entity =>
        {
            entity.Property(r => r.Id).ValueGeneratedOnAdd();
            entity.HasIndex(r => r.Name).IsUnique();
        });
        builder.Entity<ApplicationUserRole>(userRole =>
        {
            userRole.HasKey(ur => new { ur.UserId, ur.RoleId });

            userRole.HasOne(ur => ur.Role)
                .WithMany(r => r.UserRoles)
                .HasForeignKey(ur => ur.RoleId)
                .IsRequired();

            userRole.HasOne(ur => ur.User)
                .WithMany(r => r.UserRoles)
                .HasForeignKey(ur => ur.UserId)
                .IsRequired();
        });
    }
    private void SeedUsers(ModelBuilder builder)
    {
        ApplicationUser user = new ApplicationUser()
        {
            UserName = "Admin",
            NormalizedUserName = "ADMIN",
            Email = "admin@admin.com",
            SecurityStamp = Guid.NewGuid().ToString("D"),
            PhoneNumber = "+1234567890"
        };

        PasswordHasher<ApplicationUser> passwordHasher = new PasswordHasher<ApplicationUser>();
        passwordHasher.HashPassword(user, "Admin*123");

        builder.Entity<ApplicationUser>().HasData(user);
    }

    private void SeedRoles(ModelBuilder builder)
    {
        builder.Entity<ApplicationRole>().HasData(
            new ApplicationRole() { Name = "Admin", ConcurrencyStamp = "1", NormalizedName = "ADMIN" },
            new ApplicationRole() { Name = "User", ConcurrencyStamp = "2", NormalizedName = "USER" }
            );
    }

    private void SeedUserRoles(ModelBuilder builder)
    {
        builder.Entity<IdentityUserRole<long>>().HasData(
            new IdentityUserRole<long>() { RoleId = 1, UserId = 1 }
            );
    }
}

The Id are auto-generated. Id 是自动生成的。

When I did Add-Migration , I got this error:当我做Add-Migration时,我收到了这个错误:

The entity type 'IdentityUserRole' requires a primary key to be defined.实体类型“IdentityUserRole”需要定义一个主键。 If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'.如果您打算使用无密钥实体类型,请在“OnModelCreating”中调用“HasNoKey”。 For more information on keyless entity types, see https://go.microsoft.com/fwlink/?linkid=2141943 .有关无密钥实体类型的详细信息,请参阅https://go.microsoft.com/fwlink/?linkid=2141943

How do I resolve this?我该如何解决这个问题?

Thanks谢谢

you need to delete some code in AppDbContext :您需要删除AppDbContext中的一些代码:

AppDbContext AppDbContext

public class AppDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, long, IdentityUserClaim<long>, ApplicationUserRole, IdentityUserLogin<long>, IdentityRoleClaim<long>, IdentityUserToken<long>>
    {
        public AppDbContext(DbContextOptions<AppDbContext> options)
            : base(options)
        {
        }

        public DbSet<ApplicationRole> ApplicationRole { get; set; }
        public DbSet<ApplicationUserRole> ApplicationUserRole { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
           

            builder.Entity<ApplicationUser>(entity =>
            {
                entity.Property(u => u.Id).ValueGeneratedOnAdd();
                entity.HasIndex(u => u.Email).IsUnique();
            });
            builder.Entity<ApplicationRole>(entity =>
            {
                entity.Property(r => r.Id).ValueGeneratedOnAdd();
                entity.HasIndex(r => r.Name).IsUnique();
            });
            
        }
        private void SeedUsers(ModelBuilder builder)
        {
            ApplicationUser user = new ApplicationUser()
            {
                UserName = "Admin",
                NormalizedUserName = "ADMIN",
                Email = "admin@admin.com",
                SecurityStamp = Guid.NewGuid().ToString("D"),
                PhoneNumber = "+1234567890"
            };

            PasswordHasher<ApplicationUser> passwordHasher = new PasswordHasher<ApplicationUser>();
            passwordHasher.HashPassword(user, "Admin*123");

            builder.Entity<ApplicationUser>().HasData(user);
        }

        private void SeedRoles(ModelBuilder builder)
        {
            builder.Entity<ApplicationRole>().HasData(
                new ApplicationRole() { Name = "Admin", ConcurrencyStamp = "1", NormalizedName = "ADMIN" },
                new ApplicationRole() { Name = "User", ConcurrencyStamp = "2", NormalizedName = "USER" }
                );
        }

        private void SeedUserRoles(ModelBuilder builder)
        {
            builder.Entity<IdentityUserRole<long>>().HasData(
                new IdentityUserRole<long>() { RoleId = 1, UserId = 1 }
                );
        }
    }

you can read this document to learn more about Customize Identity: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/customize-identity-model?view=aspnetcore-3.1您可以阅读此文档以了解有关自定义身份的更多信息: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/customize-identity-model?view=aspnetcore-3.1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET Core MVC 错误 - 实体类型“AspNetUserLogin”需要定义主键 - ASP.NET Core MVC error - The entity type 'AspNetUserLogin' requires a primary key to be defined ASP.NET CORE 2 - 实体类型'IdentityUserRole<int> ' 是用一个键属性定义的,但是有 2 个值被传递给了 'DbSet.Find' 方法</int> - ASP.NET CORE 2 - Entity type 'IdentityUserRole<int>' is defined with a single key property, but 2 values were passed to the 'DbSet.Find' method EF Core:实体类型“用户”需要定义主键 - EF Core: The entity type 'User' requires a primary key to be defined 实体类型需要在EF Core 2.0中定义主键 - The entity type requires a primary key to be defined in EF Core 2.0 实体类型“流”需要定义一个主键。 .Net 核心 2.1 - The entity type 'stream' requires a primary key to be defined. .Net Core 2.1 .Net迁移实体类型'List<int> ' 需要定义主键</int> - .Net migration The entity type 'List<int>' requires a primary key to be defined ASP.NET 样板 - 实体任务需要主键 - ASP.NET Boilerplate - Entity Task Requires Primary Key Entity Framework Core 需要定义一个主键 - Entity Framework Core requires a primary key to be defined 实体类型 List 需要定义一个主键 - The entity type List requires a primary key to be defined 实体类型“X”需要定义主键 - The entity type 'X' requires a primary key to be defined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM