Click here to Skip to main content
15,889,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a source object and destination object with a enum property. One of the member of this enum property is different for each object. But I need to map it using Automapper. How I can achieve it?.
example code snippet:
Source Class:
public class SourceClass
{
public SourceClassification SourceLevel
{
get;
set;
}
}

Destination Class:
public class DestinationClass
{
public DestinationClassification input
{
get;
set;
}
}

Enum Property of Source Class:
public enum SourceClassification
{
Required = 1,
Optional = 2,
Selective = 3
}

Enum Property of Destination Class:
public enum DestinationClassification
{
Mandate= 1,
Optional = 2,
Selective = 3
}

What I have tried:

cfg.CreateMap<SourceClass,DestinationClass>()
.ForMember(s=>s.Input, d=>d.Input);
Posted
Updated 31-Jul-18 4:12am

Just configure a map for the enums:

C#
Mapper.CreateMap<SourceClassification,DestinationClassification>().ConvertUsing(val =>
{
   switch(val)
   {
      case SourceClassification.Required:
         return DestinationClassification.Mandate;
      case SourceClassification.Optional:
         return DestinationClassification.Optional;
      case SourceClassification.Selective:
         return DestinationClassification.Selective;
      default:
         return <whatever the default should be>;
   }
});


This has the benefit of being a flexible solution, so if either enum is refactored you will need to make sure to address the change in the conversion function.
 
Share this answer
 

You just need to tell AutoMapper to map SourceClass.SourceLevel to DestinationClass.Input. It will map on the value of the enum member so Mandate will map to Required.


C#
var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<SourceClass, DestinationClass>().ForMember(dest => dest.Input, opts =>
      opts.MapFrom(src => src.SourceLevel));
});

IMapper mapper = config.CreateMapper();
var source = new SourceClass
{
    SourceLevel = SourceClassification.Required,
};
var destination = mapper.Map<SourceClass, DestinationClass>(source);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900