2016-02-16 162 views
2

我的對象映射要求我傳遞源對象和其他對象,以便能夠適當地映射目標對象。但是,我無法確定一種能夠完成這項工作的方法。將其他對象傳遞給CreateMap

public class SourceDto 
{ 
    public string Value1 { get; set; } 
    public string Value2 { get; set; } 
    public string SourceValue3 { get; set; } 
    public string SourceValue4 { get; set; } 
} 

public class AnotherSourceDto 
{ 
    public string AnotherSourceValue1 { get; set; } 
    public string AnotherSourceValue2 { get; set; } 
    public string AnotherSourceValue3 { get; set; } 
    public string AnotherSourceValue4 { get; set; } 
} 

public class Destination 
{ 
    public string Value1 { get; set; } 
    public string Value2 { get; set; } 
    public string DestValue3 { get; set; } 
} 

public string ConvertToDestValue3(string sourceValue3, string anotherSourceValue2) 
{ 
    // Some logic goes here 
    return sourceValue3 + " " + anotherSourceValue2; 
} 


void Main() 
{ 

    var config = new MapperConfiguration(
    cfg =>cfg.CreateMap<SourceDto, Destination>() 
    .ForMember(dest => dest.DestValue3, 
    opt => opt.MapFrom(
     src => ConvertToDestValue3(src.SourceValue3, "" //Here I need to pass AnotherSourceDto.AnotherSourceValue2)))); 
} 

回答

3

恐怕答案就是將該屬性映射到AutoMapper之外。

下面是一個示例,您可以使用擴展方法執行此操作,因此它仍然具有使用AutoMapper完成的外觀和感覺。

// put inside a static class 
public static Destination CustomMap(
    this IMapper mapper, 
    SourceDto source, 
    AnotherSourceDto anotherSource) 
{ 
    var destination = mapper.Map<Destination>(source); 
    destination.DestValue3 = 
     source.SourceValue3 + " " + anotherSource.AnotherSourceValue2; 
    return destination; 
} 

void Main() 
{ 
    var config = new MapperConfiguration(cfg => 
     cfg.CreateMap<SourceDto, Destination>() 
      .ForMember(dest => dest.DestValue3, opt => opt.Ignore())); 

    // usage 
    var mapper = config.CreateMapper(); 
    var source = new SourceDto { /* add properties */ }; 
    var anotherSource = new AnotherSourceDto { /* add properties */ }; 
    var destination = mapper.CustomMap(source, anotherSource); 
} 
+1

此選項看起來更乾淨。我實際上已經將它作爲一種常規方法實施,我將使用這個想法。謝謝 – usaipavan