[英]Automapper and inheritance from Collection or List
我正在嘗試使用AutoMapper(v5.1.1)來映射從列表或集合繼承的對象。 映射調用不會給我一個錯誤,但是輸出是一個空列表(盡管類型正確)。
我可以獲得List<DestinationObject>
或Collection<DestinationObject>
,但是當具有從List<T>
或Collection<T>
繼承的自定義類時,它似乎不起作用。
我嘗試將第一個地圖定義擴展為包括基類( 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);
}
您只需要將sourceobject映射到destinationobject,AutoMapper將完成其余的工作,有關更多信息,請參見此鏈接。
cfg.CreateMap(typeof(SourceObject), typeof(DestinationObject));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.