I have two similar objects that I am mapping to each other using AutoMapper. I create the map by doing the following:
CreateMap<Object1, Object2>()
.ForMember(d => d.Name, o => o.MapFrom(s => s.Name))
.ForMember(d => d.Description, o => o.MapFrom(s => s.Description))
Now Object1
has a property Object3[] listOfObject3
this Object3
has an Id
property which I want to map to my Object2
property with string[] listOfObject3Ids
I tried the following but that doesn't work:
CreateMap<Object1, Object2>()
.ForMember(d => d.Name, o => o.MapFrom(s => s.Name))
.ForMember(d => d.Description, o => o.MapFrom(s => s.Description))
.ForMember(d => d.listOfObject3.Id, o => o.MapFrom(s => new [] {s.Id})
How do I solve this?
CodePudding user response:
Besides @Sebastian's answer to work with System.Linq which is correct,
you can also work with .ConvertUsing()
method.
Create mapping from
Object3
tostring
and via.ConvertUsing()
.Map member from
Object1.listOfObject3
toObject2.listOfObject3Ids
.
CreateMap<Object3, string>()
.ConvertUsing((src) => src.Id);
CreateMap<Object1, Object2>()
.ForMember(d => d.Name, o => o.MapFrom(s => s.Name))
.ForMember(d => d.Description, o => o.MapFrom(s => s.Description))
.ForMember(d => d.listOfObject3Ids, o => o.MapFrom(s => s.listOfObject3));
Reference
CodePudding user response:
You can map like this:
CreateMap<Object1, Object2>()
.ForMember(d => d.Name, o => o.MapFrom(s => s.Name))
.ForMember(d => d.Description, o => o.MapFrom(s => s.Description))
.ForMember(d => d.ListOfObject3, o => o.MapFrom(s => s.listOfObject3Ids.Select(id => new Object3 { Id = id })));
But as I already commented I am assuming your Object2 contains the list of Object3 and your Object1 contains the list with the ids. Then you could map like this:
CreateMap<Object1, Object2>()
.ForMember(d => d.Name, o => o.MapFrom(s => s.Name))
.ForMember(d => d.Description, o => o.MapFrom(s => s.Description))
.ForMember(d => d.listOfObject3Ids, o => o.MapFrom(s => s.ListOfObject3.Select(o => o.Id)));