I have a 2 enums that differ in name and indexing:
public enum TemperatureMode
{
Cool = 1,
Hot = 2
}
public enum HeatMode
{
Cool,
Hot
}
These are part of 2 parent objects:
public class CoolingUnitDTO
{
private string UnitName {get;set;}
private decimal Temperature {get;set;}
private TemperatureMode Mode {get;set;}
public CoolingUnitDTO(string unitName, decimal temperature, Temperature mode)
{
UnitName = unitName;
Temperature = temperature;
Mode = mode;
}
}
public class CoolingUnit
{
public string Name {get;set;}
public decimal Temperature {get;set;}
public HeatMode Mode {get;set;}
public CoolingUnit(string name, decimal temperature, HeatMode mode)
{
Name = name;
Temperature = temperature;
Mode = mode;
}
}
I've created mappings like this:
public class MappingProfiles : Profile
{
CreateMap<TemperatureMode, HeatMode>().ConvertUsingEnumMapping(opt => opt.MapByName()).ReverseMap();
CreateMap<CoolingUnitDTO, CoolingUnit>().ConstructUsing(source => new CoolingUnit(source.UnitName, source.Temperature, source.Mode));
}
However, this complains about source.Mode and says it can't convert from TemperatureMode to HeatMode. How can I map a nested enum as part of the ConstructUsing()?
CodePudding user response:
Ok, figured it out:
CreateMap<CoolingUnitDTO, CoolingUnit>().ConstructUsing((source, context) =>
{
var mode = context.Mapper.Map<HeatMode>(source.Mode);
return new CoolingUnit(source.UnitName, source.Temperature, mode);
});
CodePudding user response:
All you need is
CreateMap<CoolingUnitDTO, CoolingUnit>().ForCtorParam("name", o=>o.MapFrom(s=>s.UnitName));
The rest of your config can be removed. See https://docs.automapper.org/en/latest/Construction.html.