AutoMapper版本#是7.0.0。
采取以下一组课程:
public class Person
{
public string Name { get; set; }
public List<BarBase> BarList { get; set; }
}
public class PersonModel
{
public string Name { get; set; }
public List<BarModelBase> BarList { get; set; }
}
abstract public class BarBase
{
public int Id { get; set; }
}
public class Bar<T> : BarBase
{
public T Value { get; set; }
}
abstract public class BarModelBase
{
public int Id { get; set; }
}
public class BarModel<T> : BarModelBase
{
public T Value { get; set; }
}
Person
的属性BarList
类型为List<BarBase>
。 BarBase
是一个抽象类,具有通用的具体实现Bar<T>
;该列表需要包含多种类型的T
。
以下两种配置有效。注释掉的部分不按照评论中的说明工作。
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap(typeof(BarBase), typeof(BarModelBase))
.Include(typeof(Bar<string>), typeof(BarModel<string>));
cfg.CreateMap(typeof(Bar<string>), typeof(BarModel<string>));
cfg.CreateMap(typeof(Person), typeof(PersonModel));
});
var config = new MapperConfiguration(cfg =>
{
//Fails with: System.NullReferenceException : Object reference not set to an instance of an object.
//cfg.CreateMap(typeof(BarBase), typeof(BarModelBase)).As(typeof(BarModel<>));
//Fails with: Missing map from AutoMapper.UnitTests.OpenGenerics+Bar`1[T] to AutoMapper.UnitTests.OpenGenerics+BarModel`1[T]. Create using Mapper.CreateMap<Bar`1, BarModel`1>.
//cfg.CreateMap(typeof(BarBase), typeof(BarModelBase))
// .Include(typeof(Bar<>), typeof(BarModel<>));
cfg.CreateMap<BarBase, BarModelBase>().ConvertUsing((source, destination, context) =>
{
System.Type sourceType = source.GetType();
System.Type structType = sourceType.GetGenericArguments()[0];
return (BarModelBase)context.Mapper.Map(source, sourceType, typeof(BarModel<>).MakeGenericType(structType));
});
cfg.CreateMap(typeof(Person), typeof(PersonModel));
cfg.CreateMap(typeof(Bar<>), typeof(BarModel<>));
});
验证任一配置是否有效:
Person person = new Person
{
Name = "Jack",
BarList = new List<BarBase>
{
new Bar<string>{ Id = 1, Value = "One" },
new Bar<string>{ Id = 2, Value = "Two" }
}
};
PersonModel personMapped = config.CreateMapper().Map<PersonModel>(person);
Assert.Equal("One", ((BarModel<string>)personMapped.BarList[0]).Value);
问题:我无法让AutoMapper的Open Generics适用于这种情况(Generic<T>
扩展Non-Generic
)而没有转换器(“ConvertUsing”)或显式映射每个封闭的泛型类型
问题:我错过了什么? - 我是否可以在不使用转换器的情况下使用开箱即用的类型映射配置?