2017-06-08 58 views
1

我有兩個類並使用Automapper將其映射到另一個類。例如:Automapper。如果源成員爲null,則映射

public class Source 
{ 
    // IdName is a simple class containing two fields: Id (int) and Name (string) 
    public IdName Type { get; set; } 

    public int TypeId {get; set; } 

    // another members 
} 

public class Destination 
{ 
    // IdNameDest is a simple class such as IdName 
    public IdNameDest Type { get; set; } 

    // another members 
} 

然後我用Automapper映射SourceDestination

cfg.CreateMap<Source, Destination>(); 

它工作正常,但有時成員TypeSource變得null。在這些情況下,我想從TypeId屬性映射成員TypeDestination。這就是我想要的:

if Source.Type != null 
then map Destination.Type from it 
else map it as 
    Destination.Type = new IdNameDest { Id = Source.Id } 

AutoMapper有可能嗎?

+0

https://stackoverflow.com/a/9205604/34092有幫助嗎? – mjwills

回答

4

您可以在聲明映射時使用.ForMember()方法。 像這樣:

cfg.CreateMap<Source, Destination>() 
.ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.Type != null ? src.Type : new IdNameDest { Id = src.Id })); 
+0

Gr8回答m9。 –