I have tried using a custom converted
CreateMap<ChildB, string>().ConvertUsing(src => src.Name);
But I run into the scenario when I want to sometimes get the string like above or sometimes I want to just get the Guid:
CreateMap<ChildB, Guid>().ConvertUsing(src => src.Id);
It seems to throw and error as it always converts the Name. The Objects are like this:
public class ParentA
{
public Guid Id {get;set;}
public string Name {get;set;}
public ICollection<ChildB>? {get;set;}
...
}
public class ChildB
{
public Guid Id {get;set;}
public string Name {get;set;}
...
}
public class ParentADTO1
{
public Guid Id {get;set;}
public string Name {get;set;}
public ICollection<string> ChildNames{get;set;}
...
}
public class ParentADTO2
{
public Guid Id {get;set;}
public string Name {get;set;}
public ICollection<Guid> ChildIds {get;set;}
...
}
So the question is, can I use the CreateMap
function like so:
CreateMap<ParentA,ParentADTO1>()
...
.ForMember(ent => ent.ChildNames, opt => opt.MapFrom(???))
CreateMap<ParentA,ParentADTO2>()
...
.ForMember(ent => ent.ChildIds, opt => opt.MapFrom(???))
Your help is greatly appreciated!!
Thanks Jon
CodePudding user response:
You can set up the mapping configuration like this (I suppose the property is named Children
):
public class ParentA
{
public Guid Id {get;set;}
public string Name {get;set;}
public ICollection<ChildB> Children {get;set;}
// ...
}
CreateMap<ParentA,ParentADTO1>()
// ...
.ForMember(ent => ent.ChildNames, opt => opt.MapFrom(x => x.Children.Select(y => y.Name).ToArray()))
CreateMap<ParentA,ParentADTO2>()
// ...
.ForMember(ent => ent.ChildIds, opt => opt.MapFrom(x => x.Children.Select(y => y.Id).ToArray()))