【问题标题】:Automapper -AutoMapper.AutoMapperMappingExceptionAutomapper -AutoMapper.AutoMapperMappingException
【发布时间】:2016-05-05 15:43:24
【问题描述】:

我尝试了 Automapper,它的映射非常简单,但它不起作用。 我正在尝试将 System.Security.Claims.Claim 类型映射到另一种类型 ClaimItem:

public class ClaimItem
{
    public string Type { get; set; }
    public string Value { get; set; }
}

但我总是得到:

AutoMapper.AutoMapperMappingException:缺少类型映射配置或不支持的映射。

映射类型:Claim -> ClaimItem System.Security.Claims.Claim -> CommonAuth.ClaimItem

目标路径:ClaimItem

来源价值: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth: 05.05.2016

这是我的配置:

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Claim, ClaimItem>(MemberList.Destination);
});

config.AssertConfigurationIsValid();

var cls = getClaims();
List<ClaimItem> list = new List<ClaimItem>();
cls.ForEach(cl => list.Add(Mapper.Map<ClaimItem>(cl)));

【问题讨论】:

  • 必须有文字说明哪里错了。你能提供所有的文字吗
  • 更新了! :-) 在我的目标类型中,我只有两个道具,类型和值,我希望从 sourceType 声明映射这两个属性。它们在源和目标中具有相同的名称。
  • 您从哪里获得 Mapper?因为它应该在版本 4 中注入
  • 这只是一个单元测试,我在其中运行代码进行测试。我以为 Mapper 是一个包装器,它有一个对配置的引用,对吧???

标签: c# automapper automapper-4


【解决方案1】:

来自the documentation,您必须从配置创建映射器。所以你的代码中应该有这样的

 private static Mapper _mapper;
    public static Mapper Mapper
    {
        get
        {
            if (_mapper == null)
            {
                var config = new MapperConfiguration(cfg =>
                {
                    cfg.CreateMap<Claim, ClaimItem>(MemberList.Destination);
                });

                config.AssertConfigurationIsValid();
                _mapper = config.CreateMapper();
            }
            return _mapper;
        }
    }

这意味着如果你有静态 Mapper 它应该从你创建的配置中创建

【讨论】:

  • 现在可以了,所以,我必须创建一个单例才能访问“映射器”,对吧?
  • @Legends 我已经更新了我的答案。所以这取决于。你可以使用单例或者你可以有工厂类来创建映射器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-31
  • 1970-01-01
  • 2016-12-22
  • 1970-01-01
  • 1970-01-01
  • 2018-10-20
相关资源
最近更新 更多