I have a source DTO like this
public class Member
{
public string MemberId {get;set;}
public string MemberType {get;set;}
public string Name {get;set;}
}
The member type can be "Person" or "Company".
And two destination classes like this
public class PersonMember
{
public int PersonMemberId {get;set;}
public string Name {get;set;}
}
public class CompanyMember
{
public int CompanyMemberId {get;set;}
public string Name {get;set;}
}
I want to use Automapper to check what the value of MemberType is in the source class and depending on that type, map to one of the two destination types.
I saw the example of conditionally mapping, but it maps the field it performs the conditional check on. I want to check the condition and map a different field.
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Foo,Bar>()
.ForMember(dest => dest.baz, opt => opt.Condition(src => (src.baz >= 0)));
});
My goal is something like this -
cfg.CreateMap<Member, PersonMember>()
.ForMember(dest => PersonMember.PersonMemberId, opt => if the source.MemberType == "Person" perform mapping from MemberId, otherwise do nothing);
cfg.CreateMap<Member, CompanyMember>()
.ForMember(dest => CompanyMember.CompanyMemberId, opt => if the source.MemberType == "Company" perform mapping from MemberId, otherwise do nothing);
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…