Skip to content

Commit

Permalink
fix(CreateUser): Fix AddUserRoles bug! (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
msmahdinejad authored Aug 18, 2024
1 parent 64dc949 commit b3dc3fe
Showing 1 changed file with 22 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.IdentityModel.Tokens;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using RelationshipAnalysis.Context;
using RelationshipAnalysis.Dto;
using RelationshipAnalysis.Enums;
Expand Down Expand Up @@ -54,10 +55,25 @@ private ActionResponse<MessageDto> SuccessResult()

private async Task AddUserRoles(CreateUserDto createUserDto, User user)
{
var roles = createUserDto.Roles.Select(r => context.Roles
.SingleOrDefault(R => R.Name == r));
roles.ToList().ForEach(r => context.UserRoles.Add(new UserRole()
{ RoleId = r.Id, UserId = user.Id }));
var roles = new List<Role>();
foreach (var roleName in createUserDto.Roles)
{
var role = await context.Roles
.SingleOrDefaultAsync(r => r.Name == roleName);

if (role != null)
{
roles.Add(role);
}
}

var userRoles = roles.Select(role => new UserRole
{
RoleId = role.Id,
UserId = user.Id
}).ToList();

await context.UserRoles.AddRangeAsync(userRoles);
await context.SaveChangesAsync();
}

Expand All @@ -71,7 +87,7 @@ private async Task<User> AddUser(CreateUserDto createUserDto)
FirstName = createUserDto.FirstName,
LastName = createUserDto.LastName,
};
context.Add(user);
await context.AddAsync(user);
await context.SaveChangesAsync();
return user;
}
Expand Down

0 comments on commit b3dc3fe

Please sign in to comment.