自定义UserStore即使使用Include也不会加载角色

时间:2016-11-29 02:55:00

标签: asp.net asp.net-identity

我正在使用Identity 2.2,我在加载Roles属性时从UserManager获取用户时遇到问题。我用自定义的FindByIdAsync重写了UserStore。调用该方法,但仍未加载角色。

public class AppUserStore : UserStore<ApplicationUser>
{
    private readonly ApplicationDbContext _context;

    public AppUserStore(ApplicationDbContext context)
        : base(context)
    {
        _context = context;
    }

    public override async Task<ApplicationUser> FindByIdAsync(string userId)
    {
        var result = await _context.ApplicationUsers.Include(x => x.Roles).FirstOrDefaultAsync(n => n.Id == userId);
        return result;
    }
}

我在上下文中也有以下相关代码。

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<ApplicationUser>().ToTable("AspNetUsers");

        modelBuilder.Entity<IdentityRole>()
            .HasKey(r => new { r.Id })
            .ToTable("AspNetRoles");

        modelBuilder.Entity<IdentityUserClaim>()
            .HasKey(r => new { r.Id })
            .ToTable("AspNetUserClaims");

        modelBuilder.Entity<ApplicationUser>().HasMany<IdentityUserRole>((ApplicationUser u) => u.Roles);
        modelBuilder.Entity<IdentityUserRole>()
            .HasKey(r => new { r.UserId, r.RoleId })
            .ToTable("AspNetUserRoles");

        modelBuilder.Entity<ApplicationUser>().HasMany<IdentityUserRole>((ApplicationUser u) => u.Roles);

        modelBuilder.Entity<IdentityUserLogin>()
            .HasKey(l => new { l.LoginProvider, l.ProviderKey, l.UserId })
            .ToTable("AspNetUserLogins");
    }

0 个答案:

没有答案