2016-06-13 56 views
-1

我知道這個問題已被詢問過一次 here但是沒有必要在自定義類型轉換器中調用Automapper.Map()方法。那麼,如果我有這種類型的結構:在自定義類型轉換器中調用Mapper.Map

class MyType 
{ 
    public double ValueToBeComputed1 { get; set; } 

    public double ValueToBeComputed2 { get; set; } 
} 

class ComplexType 
{ 
    public double ValueToBeComputed { get; set; } 
    public MyType MyProperty { get; set; } 
} 

對於要計算所有的值,我需要做出不同的積分,所以我將有複雜類型的自定義類型轉換器,以讓我們說OTHERTYPE。我的問題是,如果我能夠調用Mapper.Map()爲該自定義轉換器內的屬性MyProperty?

+0

當你試圖調用它發生了什麼修改的數據? – Rhumborl

+0

我還沒有打過電話,我只是想知道是否有可能。 – meJustAndrew

+0

我成功創建了轉換器並調用了Mapper.Map()方法。對於低的問題抱歉! – meJustAndrew

回答

1

我面臨的Automapper自定義類型轉換,其中ITypeConverter接口已經改變過時的文件後,我在這裏找到了答案: ITypeConverter interface has been changed in AutoMapper 2.0,我是能夠使產生轉換類型的一個工作原型如下:

public class ComplexTypeConverter : ITypeConverter<ComplexSourceType, ComplexDestinationType> 
{ 
    public ComplexDestinationType Convert(ResolutionContext context) 
    { 
     var source = (ComplexSourceType)context.SourceValue; 

     return new ComplexDestinationType 
     { 
      MyProperty = Mapper.Map<SourceType, DestinationType>(source.MyProperty), 
      ValueComputed = source.ValueToBeComputed + 10 
     }; 
    } 
} 

public class TypeConverter : ITypeConverter<SourceType, DestinationType> 
{ 
    public DestinationType Convert(ResolutionContext context) 
    { 
     var source= (SourceType)context.SourceValue; 
     return new DestinationType 
     { 
      ValueComputed1 = source.ValueToBeComputed1 + 10, 
      ValueComputed2 = source.ValueToBeComputed2 + 10 
     }; 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     Mapper.Initialize(cfg => { 
      cfg.CreateMap<ComplexSourceType, ComplexDestinationType>().ConvertUsing(new ComplexTypeConverter()); 
      cfg.CreateMap<SourceType, DestinationType>().ConvertUsing(new TypeConverter()); 
     }); 

     Mapper.AssertConfigurationIsValid(); 

     ComplexSourceType source = new ComplexSourceType 
     { 
      MyProperty = new SourceType 
      { 
       ValueToBeComputed1 = 1, 
       ValueToBeComputed2 = 1 
      }, 
      ValueToBeComputed = 1 
     }; 
     var dest = Mapper.Map<ComplexSourceType, ComplexDestinationType>(source); 
    } 
} 

的DEST對象持有11上的每個屬性