Reputation: 7254
I've got a case in which I need to map something like this:
public class Event
{
string Name {get;set;}
int EventType {get;set;}
SubType Sub {get;set;}
}
The problem is that the way SubType inside should be mapped is determined by the EventType
property of the Event
class. For different types of events I want different things to be mapped.
The usual way is to create maps for both Event and SubType - they are not related to each other:
map.CreateMap<EventDTO, Event>();
map.CreateMap<SubTypeDTO, SubType>();
How can I tell automapper to change behaviour in the SubType mapping based on the Event.EventType
?
PS> I know this is bad design and it really should be resolved by refactoring the whole thing ( eg. removing the EventType and creating subclasses ) Unfortunately I inherited this code and just need to resolve bugs without spending to much time.
Upvotes: 1
Views: 1963
Reputation: 854
I'm not sure if there's something to achieve this, but you could do the following:
Mapper.CreateMap<EventDTO, Event>()
.ForMember(to => to.Name, from => from.Ignore() )
.ForMember(to => to.Sub, from => from.Ignore() )
.ForMember(to => to.EventType, from => from.Ignore() )
.AfterMap((source, dest) =>
{
switch (dest.EventType)
{
case 1:
// Behaviour EventType 1
...
dest.Name = source.NameDTO + "1";
...
break;
case 2:
// Behaviour EventType 2
...
dest.Name = source.NameDTO + "2";
...
break;
default:
// Behaviour EventType 3
...
dest.Name = source.NameDTO + "0";
...
break;
}
});
Upvotes: 2