2016-10-11 91 views
1

我試圖使用AutoMapper(v5.1.1)來映射從列表或集合繼承的對象。地圖調用不會給我一個錯誤,但輸出是一個空列表(雖然是正確的類型)。自動映射器和從集合或列表繼承

我可以得到一個List<DestinationObject>Collection<DestinationObject>,但它似乎沒有工作時,從List<T>Collection<T> enherits自定義類。

我試過擴展第一個地圖定義來包含基類(List<T>),但那給了我一個StackOverflowException。

cfg.CreateMap(typeof(SourceCollection), typeof(DestinationCollection)).Include(typeof(List<SourceObject>), typeof(List<DestinationObject>)); 

我在這裏錯過了什麼?

public class SourceCollection : List<SourceObject> { 

} 

public class DestinationCollection : List<DestinationObject> { 

} 

public class SourceObject { 

    public string Message { get; set; } 
} 

public class DestinationObject { 

    public string Message { get; set; } 
} 


static void Main(string[] args) 
{ 

    AutoMapper.Mapper.Initialize(cfg => 
    { 
     cfg.CreateMap(typeof(SourceCollection), typeof(DestinationCollection)); 
     cfg.CreateMap<List<SourceObject>, List<DestinationObject>>().Include<SourceCollection, DestinationCollection>(); 
     cfg.CreateMap(typeof(SourceObject), typeof(DestinationObject)); 
    }); 

    AutoMapper.Mapper.AssertConfigurationIsValid(); 

    SourceCollection srcCol = new SourceCollection() { new SourceObject() { Message = "1" }, new SourceObject() { Message = "2" } }; 
    DestinationCollection dstCol = AutoMapper.Mapper.Map<SourceCollection, DestinationCollection>(srcCol); 
} 

回答

1

你只需要映射sourceobject到destinationobject,AutoMapper會做的魔術休息,多在此可以在此link

cfg.CreateMap(typeof(SourceObject), typeof(DestinationObject)); 
+0

哇,謝謝發現 - 從來沒有嘗試過只一行: ) 有趣的是,其他代碼行都讓AutoMapper感到困惑 - 我確定這是需要的,因爲我使用了繼承,並且在AutoMapper文檔中有一個章節。 謝謝! // Mike – Mike