2011-09-28 21 views
10

Mam następujący typ źródło:Jak AutoMapper utworzyć instancję klasy

public class Source 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string Address1 { get; set; } 
    public string Address2 { get; set; } 
    public string City { get; set; } 
    public string State { get; set; } 
    public string ZipCode { get; set; } 
} 

Mam następujące rodzaje przeznaczenia:

public class Destination 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 

    public Address HomeAddress { get; set; } 
} 

public class Address 
{ 
    public string Address1 { get; set; } 
    public string Address2 { get; set; } 
    public string City { get; set; } 
    public string State { get; set; } 
    public string PostalCode { get; set; } 
} 

stworzyłem mapowanie:

Mapper.CreateMap<Source, Destination>(); 

Jak skonfigurować moje mapowanie, aby utworzyć instancję adresu i odwzorować właściwość Address.PostalCode za pomocą t on Właściwość źródłowa ZipCode?

Odpowiedz

9

Dzięki AfterMap możesz określić sposób dalszego odwzorowywania obiektów po wykonaniu mapowania AutoMappera.

Mapper.CreateMap<Source, Destination>() 
       .AfterMap((src, dest) => 
           { 
            dest.HomeAddress = new Address {PostalCode = src.ZipCode}; 
           } 
      ); 
+0

Próbowałem tego. Nie działa. Wyrażenie "dest => Convert (dest.Address.PostalCode)" musi zostać rozpoznane jako element najwyższego poziomu. – Dismissile

+0

Ponadto, nie chcę umieszczać inicjalizacji w moim konstruktorze, ponieważ nie chcę zawsze tworzyć i adresować podczas tworzenia nowego miejsca docelowego, tylko gdy mapuję ze źródła, chcę utworzyć adres. – Dismissile

+0

@ Dismissile, To się nie udaje, ponieważ przechodzisz do 'Convert (...)' not' dest.Address.PostalCode'. Ponadto, patrząc na przykłady tutaj: https://github.com/AutoMapper/AutoMapper/wiki/Projection wygląda na to, że nie musisz uwzględniać pustego konstruktora, o ile obie klasy mają domyślne konstruktory. – scottm

Powiązane problemy