Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use AutoMapper to convert Child Object list to either list of strings or list of Guids

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);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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()))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading