我正在尝试使用从通用List<T>
类派生的附加属性映射对象的集合。我尝试了许多不同的配置,但是它们要么只返回集合中的项目,而不返回派生类的属性,要么只返回属性而不是项目。
我似乎在映射配置中缺少某些内容。我已经看到了在较早版本的AutoMapper中使用AfterMap的示例-但是我在这些版本上进行的任何尝试都导致了堆栈溢出。
下面是我的代码,并尝试了一些不同的配置。
这是使用AutoMapper 8.0.0 / 8.1.1。
public class InheritedList<T> : List<T>
{
public string Property { get; set; }
}
static class Program
{
static void Main(string[] args)
{
// Collection Items are mapped; InheritedList.Property is not mapped
var configuration1 = new MapperConfiguration(cfg =>
{
cfg.CreateMap<string, int>()
.ConstructUsing(s => s.Length);
});
// Collection Items are not mapped; InheritedList.Property is mapped
var configuration2 = new MapperConfiguration(cfg =>
{
cfg.CreateMap<string, int>()
.ConvertUsing(s => s.Length);
cfg.CreateMap<InheritedList<string>, InheritedList<int>>();
});
// Collection Items are not mapped; InheritedList.Property is mapped
var configuration3 = new MapperConfiguration(cfg =>
{
cfg.CreateMap<string, int>()
.ConvertUsing(s => s.Length);
cfg.CreateMap<InheritedList<string>, InheritedList<int>>();
cfg.CreateMap<List<string>, List<int>>()
.Include<InheritedList<string>, InheritedList<int>>();
});
// Collection Items are not mapped; InheritedList.Property is mapped
var configuration4 = new MapperConfiguration(cfg =>
{
cfg.CreateMap<string, int>()
.ConvertUsing(s => s.Length);
cfg.CreateMap<List<string>, List<int>>();
cfg.CreateMap<InheritedList<string>, InheritedList<int>>()
.IncludeBase<List<string>, List<int>>();
});
IMapper mapper = new Mapper(configuration1);
var source =
new InheritedList<string>
{
Property = "Test"
};
source.Add("ABC");
source.Add("ABCDEFG");
var destination = mapper.Map<InheritedList<string>, InheritedList<int>>(source);
Console.WriteLine(destination.Count);
Console.WriteLine(destination.Property);
}
}