AutoMapper/AutoMapper — Issue #157: Custom mapping in 1.1 broken in 2.0
Author: davidkeaveny
Created: 2011-12-09 02:30:20+00:00
State: open

I have the following entity class:

public class MyEntity
{
public string Parameters { get;set;}
}

and the following DTO:

public class MyDto
{
public string[] Parameters { get;set; }
}

The intention is that the Parameters collection is serialised as XML in the database, and deserialised for the DTO. I'm using AutoMapper profiles, so my configuration is:

public class EntityToDtoProfile : Profile
{
public override string ProfileName
{
get { return "Entity to DTO"; }
}

protected override void Configure()
{
CreateMap()
.ForMember(t => t.Parameters, o => o.MapFrom(s => Serialise.FromXml(s.Parameters)));
base.Configure();
}
}

where Serialise.FromXml is obviously a helper method which converts the XML into a string[] array. Now this code works perfectly fine in AutoMapper 1.1.0, but when I upgrade to v2.0.0, it breaks with the following error:

AutoMapper.AutoMapperMappingException was unhandled by user code
Message=Trying to map MyProject.MyEntity to MyProject.MyDto.
Using mapping configuration for MyProject.MyEntity to MyProject.MyDto
Exception of type 'AutoMapper.AutoMapperMappingException' was thrown.
Source=AutoMapper
StackTrace:
at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context)
at AutoMapper.MappingEngine.Map(Object source, Type sourceType, Type destinationType, Action`1 opts)
at AutoMapper.MappingEngine.Map[TSource,TDestination](TSource source)
at AutoMapper.Mapper.Map[TSource,TDestination](TSource source)
at MyProject.Tests.WhenMapping.Act() in C:\Svn\MyProject.Tests.WhenMapping.cs:line 43
InnerException: System.InvalidCastException
Message=Unable to cast object of type 'System.String' to type 'System.String[]'.
Source=Anonymously Hosted DynamicMethods Assembly
StackTrace:
at lambda_method(Closure , Object[] )
at AutoMapper.ConstructorMap.ResolveValue(ResolutionContext context)
at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.CreateObject(ResolutionContext context)
at AutoMapper.Mappers.TypeMapObjectMapperRegistry.NewObjectPropertyMapMappingStrategy.GetMappedObject(ResolutionContext context, IMappingEngineRunner mapper)
at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.Map(ResolutionContext context, IMappingEngineRunner mapper)
at AutoMapper.Mappers.TypeMapMapper.Map(ResolutionContext context, IMappingEngineRunner mapper)
at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context)
InnerException: