Property "UserRoles" of custom IdentityUser is always empty

39 views Asked by At

I needed to check if the company had at least one owner, so I wrote the following code:

var company = await _uow.CompanyRepository.GetCompaniesIncludedUsersByIdAsync(command.CompanyId);
if (company is null)
{
    return Error.NotFound(description: "Company with such id does not exist");
}

bool hasOwner = company.Users.Any(user => user.UserRoles.Any(userRole => userRole.Role.Name == Roles.Owner));
if (hasOwner)
{
    return Error.Forbidden(description: "The company already has an owner");
}

where

public class CompanyRepository : BaseRepository<Company>, ICompanyRepository
{
    public CompanyRepository(CimasDbContext context) : base(context) {}

    public async Task<Company> GetCompaniesIncludedUsersByIdAsync(Guid companyId)
    {
        return await Sourse
            .Include(company => company.Users)
            .ThenInclude(user => user.UserRoles)
            .ThenInclude(userRole => userRole.Role)
            .FirstOrDefaultAsync(company => company.Id == companyId);
    }
}

where

 public class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : class
 {
     protected CimasDbContext _context;
     protected DbSet<TEntity> Sourse;

     public BaseRepository(CimasDbContext context)
     {
         _context = context;
         Sourse = context.Set<TEntity>();
     }
     
     ...

To make this code work, modify app as follows:

models:

public class User : IdentityUser<Guid>
{
    public Guid CompanyId { get; set; }
    public virtual Company Company { get; set; }

    public virtual ICollection<UserRole> UserRoles { get; set; }
}
public class UserRole : IdentityUserRole<Guid>
{
    public virtual User User { get; set; }
    public virtual Role Role { get; set; }
}
public class Role : IdentityRole<Guid>
{
    public virtual ICollection<UserRole> UserRoles { get; set; }
}

dbContext:

 public class CimasDbContext
        : IdentityDbContext<User, Role, Guid>
    {
        public DbSet<Company> Companies { get; set; }

        public CimasDbContext(DbContextOptions<CimasDbContext> options) : base(options) { }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<UserRole>(builder =>
            {
                builder.HasOne(ur => ur.Role)
                    .WithMany(r => r.UserRoles)
                    .HasForeignKey(ur => ur.RoleId)
                    .IsRequired();

                builder.HasOne(ur => ur.User)
                    .WithMany(u => u.UserRoles)
                    .HasForeignKey(ur => ur.UserId)
                    .IsRequired();
            });

            base.OnModelCreating(modelBuilder);
        }
    }

method I use to register dependencies in the application:

 private static IServiceCollection AddDatabaseServices(this IServiceCollection services, IConfiguration configuration)
 {
     services.AddIdentity<User, Role>()
         .AddEntityFrameworkStores<CimasDbContext>()
         .AddDefaultTokenProviders();
     services.AddDbContext<CimasDbContext>(options =>
         options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));

     return services;
 }

I successfully created a new migration and updated the database. Added roles to the database. But as you can see, no user has UserRoles. What could be the reason? enter image description here

0

There are 0 answers