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);
Member
type as a parameter. As a result it should give you some base class forPersonMember
andCompanyMember
(object
as a first candidate). Are you satisfied with such case?Mapper.Map<PersonMember>(member)
whenmember.MemberType == "CompanyMember"
you would get the same result as if you callnew PersonMember() { Name = member.Name }
, don't you?