I'm new to AutoMapper framework. I have three to Five complex objects which has to be mapped to one object
For example ChipInfo, HardDiskInfo, MonitorInfo, MemoryCardInfo has to be mapped to LaptopInfo because LaptopInfo object has fields that has to be populated from all four objects.
How can this be achievable using AutoMapper. I couldn't find any answers which allows me to do CreateMap using .ForMember to four objects. Please help Thanks
Following is the updated Code
public class AutoMapperConfig
{
Mapper.Initialize(x =>
{
x.AddProfile<chipInfoMapperProfile>();
x.AddProfile<(hardDiskInfoMapperProfile>();
x.AddProfile<monitorInfoMapperProfile>();
x.AddProfile<memoryCardInfoMapperProfile>();
});
}
public class chipInfoMapperProfile : Profile
{
protected override void Configure()
{
Mapper.CreateProfile(Profiles.ChipProfileName).CreateMap<chipInfo, laptopInfo>()
.ForMember(x => x.LapTopChipProperty, opt => opt.MapFrom(source => source.ChipProperty));
}
}
public class hardDiskInfoMapperProfile : Profile
{
protected override void Configure()
{
Mapper.CreateProfile(Profiles.hardDiskProfileName).CreateMap<hardDiskInfo, laptopInfo>()
.ForMember(x => x.LaptopHardDiskProperty, opt => opt.MapFrom(source => source.HardDiskProperty));
}
}
public class monitorInfoMapperProfile: Profile
{
protected override void Configure()
{
Mapper.CreateProfile(Profiles.monitorInfoProfileName).CreateMap<monitorInfo, laptopInfo>()
.ForMember(x => x.LaptopMonitorInfoProperty, opt => opt.MapFrom(source => source.MonitorInfoProperty));
}
}
If you create mappings for each one of those combinations, you can use the overload that lets you map to an existing object. Here's an example.
Your code might look something like this:
var laptopInfo = new LaptopInfo();
Mapper.Map(chipInfo, laptopInfo);
Mapper.Map(hardDiskInfo, laptopInfo);
Mapper.Map(monitorInfo, laptopInfo);
Mapper.Map(memoryCardInfo, laptopInfo);
Essentially, you're just applying a mapping to an existing/destination object for each one of your source objects.