Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

Automatically adding a Role and OU to a new type of user #1693


User avatar
0
joe704la created

I have a Renter type of user setup through table per hierarchy design that I want to automatically assign a Role and OU I have setup. What is the easiest way to do this?

Originally I was going to do something similar to this. But I obviously do not have the renter id yet as I am creating the user.

//Assign renter role
            var renterRole = await _roleManager.GetRoleByNameAsync("Renter");
            if (renterRole != null)
            {
                renter.Roles.Add(new UserRole(AbpSession.TenantId, renter.Id, renterRole.Id));
            }

            //Assign to OU
            var renterOrgUnit = _organizationUnitRepository.FirstOrDefaultAsync(o => o.DisplayName.Equals("Renter"));
            if (renterOrgUnit != null)
            {
                await UserManager.AddToOrganizationUnitAsync(renter.Id, renterOrgUnit.Id);
            }

3 Answer(s)
  • User Avatar
    0
    hikalkan created
    Support Team

    Your code seems fine. Just do "await UnitOfWork.SaveChangesAsync();" to get new user's id.

  • User Avatar
    0
    joe704la created

    I can save the user roll just fine. But the OU isn't working. This below line is bringing back an Id of 3864 but the Id of the OU should be 2. So it throws an exception when it tries to save the to the link between the OU and the user because it can't find that ID.

    var renterOrgUnit = _organizationUnitRepository.FirstOrDefaultAsync(o => o.DisplayName.Equals("Renter"));
    
  • User Avatar
    0
    joe704la created

    I finally figured this out. I finally realized I needed to put the tentantId within the query. My bad.

    var renterOrgUnit = await _organizationUnitRepository.FirstOrDefaultAsync(o => o.TenantId == renter.TenantId &&  o.DisplayName.Equals("Renter"));