【问题标题】:AutoMapper Static Class Is Not Mapping List and Nested EntityAutoMapper 静态类不映射列表和嵌套实体
【发布时间】:2021-11-10 20:41:20
【问题描述】:

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

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);

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

【问题讨论】:

  • 两个代码块略有不同。您可以尝试将cfg.CreateMap&lt;TDestination,TSource&gt;().ReverseMap(); 更改为cfg.CreateMap&lt;TSource,TDestination&gt;().ReverseMap();
  • @serdar 我认为 .ReverseMap();正在做。不工作。

标签: c# .net asp.net-core .net-core automapper


【解决方案1】:

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

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

最后:

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

【讨论】:

  • 删除List时,报错“AutoMapperMappingException: Missing type map configuration or unsupported mapping.”顺便说一句,我的问题是关于第一个代码块。
【解决方案2】:

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

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<>)));

【讨论】:

  • 不工作:AutoMapperMappingException: Missing type map configuration or unsupported mapping.
猜你喜欢
  • 2020-02-04
  • 1970-01-01
  • 1970-01-01
  • 2020-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-26
相关资源
最近更新 更多