有没有办法用 Automapper 进行一对多映射?
Is there a way to do a one to many mapping with Automapper?
我正在尝试将密码(来自新用户的密码)映射到 passwordHash 和 passwordSalt。我用来创建这两个值的函数会同时生成这两个值,并且 return 它们。是否可以使用 Automapper 从单个密码映射到这两个值?
下面是我的尝试。
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)));
}
}
您可以使用 BeforeMap
或 AfterMap
,而不是使用成员映射 (ForMember
),例如:
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;
});
我正在尝试将密码(来自新用户的密码)映射到 passwordHash 和 passwordSalt。我用来创建这两个值的函数会同时生成这两个值,并且 return 它们。是否可以使用 Automapper 从单个密码映射到这两个值? 下面是我的尝试。
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)));
}
}
您可以使用 BeforeMap
或 AfterMap
,而不是使用成员映射 (ForMember
),例如:
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;
});