ASP .NET Core 2.1身份:UserRoles为空

时间:2018-10-11 17:29:43

标签: razor asp.net-core asp.net-identity asp.net-core-2.1

在我的Razor Web应用程序中,我尝试通过以下方式获取用户及其角色的列表:

_userManager.GetUsersInRoleAsync(role).Result;
_dbContext.Users.Include(u => u.UserRoles).ThenInclude(u => u.Role);
_userManager.Users.Include(u => u.UserRoles).ThenInclude(ur => ur.Role).ToList();

并且UserRoles始终为null。知道我在做什么错吗?

这是我的创业公司:

services.AddIdentity<ApplicationUser, ApplicationRole>()
    .AddDefaultUI()
    .AddDefaultTokenProviders()
    .AddEntityFrameworkStores<ApplicationDbContext>();

这是我的模特:

public class ApplicationUser : IdentityUser
{
    public virtual ICollection<ApplicationUserRole> UserRoles { get; set; }
}

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

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

这是我的OnModelCreating:

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

        builder.Entity<ApplicationUser>(au =>
        {
            au.HasMany(e => e.UserRoles).WithOne(e => e.User).HasForeignKey(ur => ur.UserId).IsRequired();
        });

        builder.Entity<ApplicationRole>(ar =>
        {
            ar.HasMany(e => e.UserRoles).WithOne(e => e.Role).HasForeignKey(ur => ur.RoleId).IsRequired();
        });

        builder.Entity<ApplicationUserRole>(aur =>
        {
            aur.HasOne(ur => ur.Role).WithMany(r => r.UserRoles).HasForeignKey(ur => ur.RoleId).IsRequired();
            aur.HasOne(ur => ur.User).WithMany(r => r.UserRoles).HasForeignKey(ur => ur.UserId).IsRequired();
        });
    }

0 个答案:

没有答案