【发布时间】:2018-06-06 19:15:48
【问题描述】:
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。
以下两种配置有效。注释掉的部分不像 cmets 中解释的那样工作。
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)。
问题:我错过了什么? - 我可以在这里使用开箱即用的类型映射配置而不使用转换器吗?
【问题讨论】:
标签: c# automapper open-generics