3

以下映射代码导致 automapper 在映射完成时抛出异常。

mapper.CreateMap<SqlDataReader, CodeModel>()
      .ForMember(dest => dest.Code, 
                 options => options.MapFrom(src => src["code"] != null ? 
                                                   src["code"].ToString() :
                                                   string.Empty));

这真的很奇怪,src["code"]有一个价值,它是"E",这甚至在 automapper 消息中都有说明。

有没有人对这个问题或如何解决这个问题有任何见解?

堆栈跟踪:

[NullReferenceException:对象引用未设置为对象的实例。] AutoMapper.Mappers.TypeMapMapper.Map(ResolutionContext 上下文,IMappingEngineRunner 映射器)+116
AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext 上下文)+459

[AutoMapperMappingException:

映射类型:字符串 -> 字符串 System.String -> System.String

目标路径:CodeModel.Code

源值:E]
AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context) +537
AutoMapper.Mappers.DataReaderMapper.MapPropertyValue(ResolutionContext context, IMappingEngineRunner mapper, Object mappedObject, PropertyMap propertyMap) +305
AutoMapper.Mappers.DataReaderMapper.MapPropertyValues( ResolutionContext context, IMappingEngineRunner mapper, Object result) +210
AutoMapper.Mappers.DataReaderMapper.Map(ResolutionContext context, IMappingEngineRunner mapper) +639
AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context) +477 AutoMapper.MappingEngine.Map(Object source , 输入 sourceType, 输入destinationType, Action 1 opts) +1621 opts) +176
AutoMapper.MappingEngine.Map(Object source, Action

AutoMapper.MappingEngine.Map(对象源)+143

4

1 回答 1

0

尝试使用ResolveUsingmethod 而不是 method MapFrom,但在您的情况下,这两种方法都应该按预期工作。尝试查看是否存在任何配置问题。

  mapper.CreateMap<SqlDataReader, CodeModel>()
          .ForMember(dest => dest.Code, 
                     options => options.ResolveUsing(src => src["code"] != null ? 
                                                       src["code"].ToString() :
                                                       string.Empty));

我用 SqlReaderMock 创建了一个工作示例。我假设您的 SqlReader 执行上下文很好。

//Arrange
var configStore = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.AllMappers());
configStore.CreateMap<SqlDataReaderMock, Destination>()
    .ForMember(dest => dest.Name, opt => opt.ResolveUsing(src => src["tyto"] != null
                                                                        ? src["tyto"].ToString()
                                                                        : String.Empty));
var _mappingEngine = new MappingEngine(configStore);

//Act
var result = _mappingEngine.Map<Destination>(new SqlDataReaderMock());

//Assert
Assert.AreEqual("otyt", result.Name);


class Destination
{
    public string Name { get; set; }
}


class SqlDataReaderMock
{
    public string this[string value]
    {
        get
        {
            return new string(value
                                    .ToCharArray()
                                    .Reverse()
                                    .ToArray());
        }
    }
}
于 2012-08-22T06:17:13.430 回答