Is there a way to do a one to many mapping with Automapper?

Viewed 60

I'm trying to map a password (comming in from a new user) to passwordHash and passwordSalt. The function I'm using to create these two values generates both values at the same time and return them. Is it possible to map to both of these values from the single password using Automapper? This is my attempt below.

public class Users {
    string passwordSalt {get; set;}
    string passwordHash {get; set;}
}

public class UserDto {
    string password
}

public class EncryptPassword {
    public static (string, string) encryptPassword(string password) {
        //stuff happening to create passwordHash and passwordSalt
        return (passwordHash, passwordSalt)
    }
}

public class MappingProfile : Profile {
    public MappingProfile() {
        CreateMap<UserDto, Users>()
            .ForMember(dest => new Tuple<string, string>(dest.passwordSalt, dest.passwordHash), opt => opt.MapFrom(src => EncryptPassword.SHA512Password(src.password)));
    }
}
1 Answers

Instead of using a member mapping (ForMember), you could use BeforeMap or AfterMap, e.g.:

CreateMap<UserDto, Users>()
  .ForMember(x => x.passwordSalt, x => x.Ignore())
  .ForMember(x => x.passwordHash, x => x.Ignore())
  .AfterMap((dto, users) => {
    var pwd = EncryptPassword.encryptPassword(dtp.password);
    users.passwordHash = pwd.passwordHash;
    users.passwordSalt = pwd.passwordSalt;
  });
Related