Reputation: 331
This additional requirement based on this question one source to mutiple destination
class Dest1
{
string prop1;
string prop2;
string prop3;
pubic List<Dest3> Dests3 {get;set;}
}
class Dest3
{
string prop7;
string prop8;
}
class Source2
{
string prop7;
string prop8;
}
My mappping class:(not working)
CreateMap<Source2, Dest3>();
CreateMap<Source2, Dest1>()
.ForMember(d => d.Dests3 , opt => opt.MapFrom(s => s));
Upvotes: 3
Views: 433
Reputation: 339
So, assuming that when this mapping occurs Dests3 should be a single item list, the configuration for this should look something like this:
var configuration = new MapperConfiguration(cfg =>
// Mapping Config
cfg.CreateMap<Source2, Dest1>()
.ForMember(dest => dest.prop1, opt => opt.Ignore())
.ForMember(dest => dest.prop2, opt => opt.Ignore())
.ForMember(dest => dest.prop3, opt => opt.Ignore())
.ForMember(dest => dest.Dests3, opt => opt.MapFrom(src =>
new List<Dest3> {
new Dest3 {
prop7 = src.prop7,
prop8 = src.prop8
}
}));
// Check AutoMapper configuration
configuration.AssertConfigurationIsValid();
Then, you can use the mapper to handle the mapping wherever you need, like so:
public class Foo {
private IMapper _mapper;
public Foo(IMapper mapper) {
_mapper = mapper;
}
// Map Source2 -> Dest1
public Dest1 Bar(Source2 source) {
return _mapper.Map<Dest1>(source);
}
}
Upvotes: 2