AutoMapper静态类不是映射列表和嵌套实体



我使用静态类来映射我的实体。但是如果我使用下面的代码,它不能用于转换列表和嵌套实体;

public static class MapperUtil<TSource, TDestination>
{
private static readonly Mapper _mapper = new Mapper(new MapperConfiguration(
cfg =>
{
cfg.CreateMap<TDestination,TSource>().ReverseMap();
}));
public static TDestination Map(TSource source)
{
return _mapper.Map<TSource,TDestination>(source);
}
}

但是如果我使用下面的代码,它工作得很好。

var mapper = new Mapper(new MapperConfiguration(cfg =>
{
cfg.CreateMap<List<User>, List<UserDto>>().ReverseMap();
}));
List<UserDto> userDto = mapper.Map<List<User>,List<UserDto>> (users);

有人能帮我吗?(我是新手)。使用静态类进行映射是好主意吗?您将映射为静态类的解决方案是什么?

您应该在CreateMap方法中删除List并为您的类型创建映射:

var mapper = new Mapper(new MapperConfiguration(cfg =>
{
cfg.CreateMap<User, UserDto>().ReverseMap();
}));

最后:

List<UserDto> userDto = mapper.Map<List<UserDto>>(users);

如果您使用泛型类型进行映射,请尝试下面的代码

public class Source<T> {
public T Value { get; set; }
}
public class Destination<T> {
public T Value { get; set; }
}
// Create the mapping
var configuration = new MapperConfiguration(cfg => cfg.CreateMap(typeof(Source<>), typeof(Destination<>)));