Below is my class
class Dest1
{
string prop1;
string prop2;
strig prop3;
public Dest2 Dest2 {get;set;}
pubic List<Dest3> Dest3 {get;set;}
}
class Dest2
{
string prop4;
string prop5;
strig prop6;
}
class Dest3
{
string prop7;
}
class Source1
{
string prop1;
string prop2;
string prop3;
string prop4;
}
class Source2
{
string prop7;
}
I need to map
Q1. source1 class to Dest1 Class( also i need to map dest2 object)
Edit:
Q2. I need to do map Dest1 back to Source 1 (reverse map)
Am using .net core and auto mapper.. am new to automapper & .net core ..Thanks in advance
AutoMapper can map from as many sources to as many destinations as you would like, assuming you configure the mapping. For example, your requested scenario:
var configuration = new MapperConfiguration(cfg =>
// Mapping Config
cfg.CreateMap<Source1, Dest2>()
.ForMember(dest => dest.prop5, opt => opt.Ignore())
.ForMember(dest => dest.prop6, opt => opt.Ignore());
cfg.CreateMap<Source1, Dest1>()
.ForMember(dest => dest.Dest2, opt => opt.MapFrom(src => src));
// Reverse Mapping Config
cfg.CreateMap<Dest1, Source1>()
.ForMember(dest => dest.prop4,
opt => opt.MapFrom(src => (src?.Dest2 != null) // ?. w/c#6
? src.Dest2.prop4 // map if can
: null)); // otherwise null
);
// Check AutoMapper configuration
configuration.AssertConfigurationIsValid();
Properties with the same name will map automatically. Any destination properties that don't have a corresponding source property will need to be ignored.
Once your AutoMapper is configured, you can map as needed with the use of the IMapper interface.
public class Foo {
private IMapper _mapper;
public Foo(IMapper mapper) {
_mapper = mapper;
}
// Map Source1 -> Dest1
public Dest1 Bar(Source1 source) {
return _mapper.Map<Dest1>(source);
}
// Map Dest1 -> Source1
public Source1 Baz(Dest1 dest) {
return _mapper.Map<Source1>(dest);
}
}
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.