从Datatable到泛型类型的基于自动映射器的转换不起作用



我正在使用Automapper将数据表转换为泛型类型。这是我的代码

    public T MapTo<T>(DataTable table)
    {
        if (table == null || table.Rows.Count == 0)
        {
            return default(T);
        }
        else
        {
            return (T)Convert.ChangeType(AutoMapper.Mapper.DynamicMap<IDataReader, List<T>>(table.CreateDataReader())[0], typeof(T));
        }
    }

我的数据表有13列,我将其映射到的类型也是如此,但我在上面的其他块中仍然得到一个错误:

"消息":"发生错误。","ExceptionMessage":"索引超出范围。必须是非负数并且小于集合的大小。\r\n参数名称:Index","ExceptionType":"System.ArgumentOutOfRangeException","StackTrace":"位于System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument参数,ExceptionResource资源)\r\n位于System.Collections.Generic.List`1.get_Item(Int32索引)\r\n位于MySolution.GenericMap.MapTo[T](DataTable表)

可能出了什么问题?我使用的是Automapper 4.1.1.0和.Net 4.5

它在Automapper 4.0.0+版本中似乎已损坏(请参阅错误报告)

此链接错误报告建议降级到3.3.1版本或使用以下程序:

DataReaderMapper应该存在。我从DataReaderMapper(3.1版)中提取了一个旧版本并注册了它,现在它可以工作了。

寄存器映射器:

MapperRegistry.Mappers.Add(new DataReaderMapper());

DataReaderMapper的代码:

https://github.com/AutoMapper/AutoMapper/blob/v3.3.1/src/AutoMapper/Mappers/DataReaderMapper.cs

必须更改以下代码:

TypeMap typeMap = configurationProvider.FindTypeMapFor(context.SourceValue, context.DestinationValue, context.SourceType, destinationElementType);

新代码:

Map typeMap = configurationProvider.FindTypeMapFor(context.SourceType, destinationElementType);

if (context.TypeMap == null)
    {                
        throw new AutoMapperMappingException(context, "Missing type map configuration or unsupported mapping.");
    }

if (context.TypeMap == null)
        {                
            return;
        }

虽然前面的过程可以工作,但错误报告还链接到一个nuget包,其中包含旧DataReaderMapper的代码,但它在我的机器上不适用于DynamicMap。

最新更新