【问题标题】:AutoMapper. Missing type map configuration自动映射器。缺少类型映射配置
【发布时间】:2016-06-23 09:45:44
【问题描述】:

我有用于初始化映射器配置文件的单例 EntityMapper 类。

    private readonly IMapper _mapper;
    private static EntityMapper _instance;
    public static EntityMapper Instance => _instance ?? (_instance = new EntityMapper());
    private EntityMapper()
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile(new ViewColumnMapperProfile());
        });
        _mapper = config.CreateMapper();
    }

在基本 Profile 类中:

public class BaseMapperProfile<TSorce, TTarget> : Profile
{
    protected override void Configure()
    {
        CreateMap<List<TSorce>, IdentityList>()
            .ForCtorParam("identities", opt => opt.MapFrom(src => Mapper.Map<Identity>(src)));
        CreateMap<IdentityList, List<TSorce>>()
            .ConstructUsing(scr => new List<TSorce>(scr.Select(Mapper.Map<TSorce>)));
    }
}

还有子类:

public class ViewColumnMapperProfile : BaseMapperProfile<AP_ViewColumn, ColumnInfo>
{
    protected override void Configure()
    {
        CreateMap<AP_ViewColumn, ColumnInfo>()
            .ForMember(...)
        CreateMap<ColumnInfo, AP_ViewColumn>()
            .ForMember(...)

        CreateMap<AP_ViewColumn, Identity>()
            .ForMember(...)
        CreateMap<Identity, AP_ViewColumn>()
            .ForMember(...);

        base.Configure();
    }
}

然后我使用映射:

    var res = EntityMapper.Map<List<AP_ViewColumn>>(identityList);

并且这段代码抛出异常:Missing type mao configuration or unsupported mappig。

映射类型: 身份 -> AP_ViewColumn

但是当我使用时:

Mapper.Initialize(cfg => cfg.AddProfile(new ViewColumnMapperProfile())); 
var res = EntityMapper.Map<List<AP_ViewColumn>>(identityList);

没关系

【问题讨论】:

    标签: automapper


    【解决方案1】:

    你的问题已经有了答案。

    当您使用var res = EntityMapper.Map&lt;List&lt;AP_ViewColumn&gt;&gt;(identityList); 时,您使用自己的包装器,该包装器配置和使用Mapper 类的实例

    但是,在您的 BaseMapperProfile 中,您可以调用静态方法 Mapper.Map&lt;Identity&gt;(src)

    但在您的EntityMapper 中,您仅为Mapperinstance 配置/提供了所有映射,不适用于 static Mapper

    解决需要通过Mapper.Initialize方法配置static Mapper

    目前,我还没有找到如何在其中传递映射器实例的方法(我认为它将在目前处于测试阶段的 5.0 版本中实现)。

    【讨论】:

      猜你喜欢
      • 2019-08-10
      • 1970-01-01
      • 1970-01-01
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-10
      相关资源
      最近更新 更多