简体   繁体   English

Automapper:映射继承自 List 的两种类型<keyvaluepair<string, string> &gt;&gt; </keyvaluepair<string,>

[英]Automapper : mapping two types inherited from List<KeyValuePair<string, string>>>

Let's assume I have these types:假设我有这些类型:

public class MetadataList1 : List<KeyValuePair<string, string>>
{

}

public class MetadataList2 : List<KeyValuePair<string, string>>
{

}

I would like to be able to map one to the other with last version of Automapper (10.1.1):我希望能够使用 Automapper 的最新版本(10.1.1)一对一地 map:

var metadataList = _mapper.Map<MetadataList2>(metadataList1);

But list items are not copied, the resulting list always have a count of 0.但不会复制列表项,结果列表的计数始终为 0。

I tried the most naive configuration:我尝试了最幼稚的配置:

cfg.CreateMap<MetadataList1, MetadataList2>().ReverseMap();

And a few other things:还有其他一些事情:

cfg.CreateMap<KeyValuePair<string, string>, KeyValuePair<string, string>>();
cfg.CreateMap<List<KeyValuePair<string, string>>, List<KeyValuePair<string, string>>>();
cfg.CreateMap<MetadataList1, MetadataList2>()
    .IncludeBase<List<KeyValuePair<string, string>>, List<KeyValuePair<string, string>>>()
    .ReverseMap();

I can't figure how to have it working, and I didn't find the answer, especially because Automapper configuration and usage seems to have changed several times these years regarding this kind of usage.我不知道如何让它工作,也没有找到答案,特别是因为这些年来 Automapper 的配置和使用似乎已经改变了好几次这种用法。

In general if you map two types with Automapper, collection mapping comes for free.一般来说,如果您使用 Automapper 的 map 两种类型,则集合映射是免费的。 Eg if I mapped type MyClass Automapper would map List<MyClass> without extra set up.例如,如果我映射类型MyClass Automapper 将 map List<MyClass>没有额外的设置。 However your type is itself a collection, and I guess Automapper does not find public properties to map there.但是,您的类型本身就是一个集合,我猜 Automapper 在那里找不到 map 的公共属性。

I would suggest to use a custom converter:我建议使用自定义转换器:

cfg.CreateMap<MetadataList1, MetadataList2>().ConvertUsing<MyConverter>();

public class MyConverter : ITypeConverter<MetadataList1, MetadataList2>
{
  public MetadataList1 Convert(MetadataList2 source, MetadataList1 destination, ResolutionContext context) 
  {
    // iterate over first list and copy elements to the second list
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM