I’ve been running into some strange errors originating in Automapper over the past few months but I believe I’ve found the cause and a workaround. The strange part is that the errors only occur when my application is running in production. Running the app on my local dev box and there are no errors. The file version of Automapper I’m currently using (though I’ve seen this behavior in previous versions) is 184.108.40.206. I hesitate to call this error a bug because I believe the differing behavior is a result of different .Net framework versions in production vs my local machine. Details of the exception (with stack trace to my app removed)
Exception of type 'AutoMapper.AutoMapperMappingException' was thrown. at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context) at AutoMapper.MappingEngine.Map(Object source, Type sourceType, Type destinationType) at AutoMapper.MappingEngine.Map[TSource,TDestination](TSource source) at AutoMapper.Mapper.Map[TSource,TDestination](TSource source) Common Language Runtime detected an invalid program. at DynamicCreate(IDataRecord ) at AutoMapper.Mappers.DataReaderMapper.Map(ResolutionContext context, IMappingEngineRunner mapper) at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context)
The production box is Windows Server 2003 R2 with .Net framework version 3.5.30729.01. My dev box is a Windows 7 Pro with .Net framework version 3.5.30729.4926. The framework versions is the only difference I can come up with.
The error “Common Language Runtime detected an invalid program” is actually the result of invalid mappings from an IDataReader (actually a SqlDataReader) to an object model. After seeing some invalid data in my objects that certainly did not exist in the database I discovered there are differences between .Net float and Sql Server float as well as issues mapping a Sql money data type to a .Net double. There exists an MSDN page, which I currently can’t find, that indicates a Sql float should be mapped to .Net double and Sql Money should be mapped to .Net float. When I explicitly set these mappings in Automapper the errors when away in production! Not sure what the purpose of the DataReader.GetFloat method is if it can’t pull float values from Sql Server but specifying GetDouble on a column that is a Sql Server float works perfectly.
What I’m trying to understand is why the production server threw errors trying to do this mapping while my local dev box kept chugging along and filled the data models with invalid data as a result of mapping the Sql float to a .Net float. If you’re seeing invalid program exceptions, maybe there are some invalid mappings! Something to look out for.