I am implementing update user endpoint. During update, I am fetching original entity.
public class UserEntity
{
public Guid Id { get; set; }
public Dictionary<string, IEnumerable<string>> Attributes { get; set; }
}
var user = await _userService.GetByIdAsync(request.Id);
Then I have an update request
public class UpdateUserRequest
{
public string? MiddleName { get; set; }
public string? Phone { get; set; }
}
MiddleName
and Phone
should be stored as attributes here.
_mapper.Map(request, user);
CreateMap<UpdateUserRequest, UserEntity>().ForMember(dst => dst.Attributes, opt => opt.UseDestinationValue());
I am using destination values to preserve original attributes, because if not, they will be emptied.
My solution to preserve original attributes and put new ones is kinda dirty and my question is: can I handle it with Automapper's help?
My solution:
void SetAttributes()
{
if(!string.IsNullOrEmpty(request.MiddleName))
{
if(!user.Attributes.TryGetValue(Constants.Attributes.MiddleName, out var middleName))
{
user.Attributes.Add(Constants.Attributes.MiddleName, new string[]
{
request.MiddleName
});
}
else
{
user.Attributes[Constants.Attributes.MiddleName] = new string[]
{
request.MiddleName
};
}
}
if(!string.IsNullOrEmpty(request.Phone))
{
if(!user.Attributes.TryGetValue(Constants.Attributes.PhoneNumber, out var firstName))
{
user.Attributes.Add(Constants.Attributes.PhoneNumber, new string[]
{
request.Phone
});
}
else
{
user.Attributes[Constants.Attributes.PhoneNumber] = new string[]
{
request.Phone
};
}
}
}
Figured this out with AfterMap()
method of automapper.
.AfterMap((request, user) =>
{
if(!string.IsNullOrEmpty(request.FirstName))
{
user.FirstName = request.FirstName;
}
if(!string.IsNullOrEmpty(request.LastName))
{
user.LastName = request.LastName;
}
if(!string.IsNullOrEmpty(request.Email))
{
user.Email = request.Email;
}
if(!string.IsNullOrEmpty(request.MiddleName))
{
if(!user.Attributes.TryGetValue(KeycloakConstants.Attributes.MiddleName, out _))
{
user.Attributes.Add(KeycloakConstants.Attributes.MiddleName, new string[]
{
request.MiddleName
});
}
else
{
user.Attributes[KeycloakConstants.Attributes.MiddleName] = new string[]
{
request.MiddleName
};
}
}
if(!string.IsNullOrEmpty(request.Phone))
{
if(!user.Attributes.TryGetValue(KeycloakConstants.Attributes.PhoneNumber,
out _))
{
user.Attributes.Add(KeycloakConstants.Attributes.PhoneNumber, new string[]
{
request.Phone
});
}
else
{
user.Attributes[KeycloakConstants.Attributes.PhoneNumber] = new string[]
{
request.Phone
};
}
}
});