Basically, I have a DateTime in one Class that is on the ‘surface’ and another DateTime that’s part of a Class within a Complex property of another Class and I’m wanting to map back and forth between these DateTime Types…
public class AModel {
DateTime DateFrom { get;set; }
DateTime DateThru { get;set; }
}
public class BModel {
ModelDateCollection DateFromClass { get;set; }
ModelDateCollection DateThruClass { get;set; }
}
public class ModelDateCollection {
DateTime Date { get;set; }
String Display { get; } // Example Readonly for Date Display
DateTime FirstOfMonth { get; } // Another Example to extend Complex Class
}
For the initialization of the Map I am using:
CreateMap<BModel, AModel>()
.ForMember(d => d.DateFrom, s => s.MapFrom(src => src.DateFromClass.Date))
And, as you can see, I am attempting to map the Property DateFromClass.Date to the destination DateFrom.
I also intend to map in the other direction as well:
CreateMap<AModel, BModel>()
.ForMember(d => d.DateFrom, s => s.MapFrom(src => new ModelDateCollection(src.DateFrom)))
According to the Exception below, I am not able to map these DateTime values back and forth as is.
Unable to cast object of type ‘System.DateTime’ to type
‘ModelDateCollection’.->Trying to map AModel to BModel
Using mapping configuration for AModel to BModel
Exception of type ‘AutoMapper.AutoMapperMappingException’ was thrown.
Any suggestions?
OK…it’s all been resolved. Turns out that the example is slightly off since I wasn’t sure of the problem to begin with. As you’ll see in my Class Definition, DateFrom & DateFromClass share different names…well, in my example, they actually had the same name…so, the new class structure would be as follows ::
Here’s the clincher…even though the types are different, Automapper first wants to map from an item with one name to a matching member with the same name…regardless of type! So, the painful answer was just to rename the properties if your going to go and make this attempt to map…currently Automapper does not look at name AND type before looking to your bootstrapper to apply any custom logic.