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);
问题:如果没有转换器(“ConvertUsing”)或通过显式映射每个封闭的泛型类型,我无法让 AutoMapper 的开放泛型适用于这种情况(Generic<T>
扩展)。Non-Generic
问题:我错过了什么?-是否有一个开箱即用的类型映射配置我可以在这里使用而不使用转换器?