obiekty mapujące automapper
Aug 29 2020
Ten dodatkowy wymóg oparty na tym pytaniu jedno źródło do wielu miejsc docelowych
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;
}
- Muszę zmapować Source2 na Dest1 w automatycznym mapowaniu (Dest3 to lista również do zmapowania)
Moja klasa mapowania: (nie działa)
CreateMap<Source2, Dest3>();
CreateMap<Source2, Dest1>()
.ForMember(d => d.Dests3 , opt => opt.MapFrom(s => s));
Odpowiedzi
2 reynoldsbj Aug 30 2020 at 04:30
Zakładając więc, że gdy nastąpi to mapowanie, Dests3 powinien być listą pojedynczych elementów, konfiguracja dla tego powinna wyglądać mniej więcej tak:
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();
Następnie możesz użyć programu mapującego do obsługi mapowania w dowolnym miejscu, na przykład:
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);
}
}