I am trying to map an object with a collection property to another object with a nested class containing mapped versions of the source collections, but I can't seem to figure out the appropriate mapping required.
Below are my class and attempted mappings.
public class TypeA
{
public int Id;
public string Description;
}
public class TypeB
{
public int Id;
public int Code;
}
public class Source
{
public ICollection<TypeA> A;
public ICollection<TypeB> B;
}
public class Destination
{
public DestinationInner Inner;
}
public class DestinationInner
{
public ICollection<int> A;
public ICollection<int> B;
}
I have the following mappings defined, which works fine when the destination collection is at the parent level and not in the DestinationInner class.
Mapper.CreateMap<TypeA, int>()
.ConvertUsing(a => a.Id);
Mapper.CreateMap<TypeB, int>()
.ConvertUsing(b => b.Id);
I've tried adding a map such as, but I can't find a way of forcing a mapping here on the collections
Mapper.CreateMap<Source, Destination>()
.ForMember(d => d.Inner,
opt.MapFrom(s => new DestinationInner()
{
// not sure if I can assign anything here
A =
B =
}));
Is MapFrom the appropriate method to use here - or am I approaching this from the wrong direction?
The alternative is to not use AutoMapper for the collections and just use Linq, but I'm thinking there has to be a way to fully use AutoMapper:
Mapper.CreateMap<Source, Destination>()
.ForMember(d => d.Inner,
opt.MapFrom(s => new DestinationInner()
{
A = s.A.Select(a => a.Id).ToList(),
B = s.B.Select(b => b.Id).ToList(),
}));
Lucian provided the answer in the comments:
ForPath(d => d.Inner.A, o => o.MapFrom(s => s.A))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.