I have tried created a custom type converter using automapper, but I cannot get to work – or even compile for that matter.
Here is my custom converter:
public class WorkPlanToWorkingTimeListConverter : ITypeConverter<TPWorkPlanDTO, IEnumerable<WorkingTime>>
{
public IEnumerable<WorkingTime> Convert(TPWorkPlanDTO source, IEnumerable<WorkingTime> destination, ResolutionContext context)
{
if (source == null)
{
return Enumerable.Empty<WorkingTime>();
}
return (IEnumerable<WorkingTime>)source.Weeks.SelectMany(week => week.Days.SelectMany(day => day.Shifts));
}
}
I am trying to wire it up like this:
CreateMap<TPWorkPlanDTO, List<WorkingTime>>()
.ConvertUsing<WorkPlanToWorkingTimeConverter>();
But I get this error:
The type ‘Mapping.Converter.WorkPlanToWorkingTimeListConverter’ cannot be used as type parameter ‘TTypeConverter’ in the generic type or method ‘IMappingExpressionBase<TPWorkPlanDTO, List, IMappingExpression<TPWorkPlanDTO, List>>.ConvertUsing()’. There is no implicit reference conversion from ‘Mapping.Converter.WorkPlanToWorkingTimeListConverter’ to ‘AutoMapper.ITypeConverter<TPWorkPlanDTO, System.Collections.Generic.List<Models.WorkingTime>>’.
I have tried some of the overloads of ConvertUsing()
taking types, but I just can not make it compile.
Underneath I have attached my DTO and model I need to map:
namespace Mapping.DTO;
public class TPWorkPlanDTO
{
public class TPWorkingTimeDTO
{
public int worktime_id { get; set; }
public DateTime start_time { get; set; }
public DateTime end_time { get; set; }
}
public class TPWorkPlanDay
{
public IEnumerable<TPWorkingTimeDTO> Shifts { get; set; }
}
public class TPWorkPlanWeek
{
public IEnumerable<TPWorkPlanDay> Days { get; set; }
}
public IEnumerable<TPWorkPlanWeek> Weeks { get; set; }
}
namespace Models;
public class WorkingTime
{
public int Id { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
}
2
WorkPlanToWorkingTimeListConverter : ITypeConverter<TPWorkPlanDTO, IEnumerable<WorkingTime>>
defines a mapping to IEnumarable<...>
. And because generic type T1<T2, IEnumerable<T3>>
is different than T1<T2, List<T3>>
, this converter needs to be used as a mapping to IEnumerable<...>
, not to List<...>
:
CreateMap<TPWorkPlanDTO, IEnumerable<WorkingTime>>()
.ConvertUsing<WorkPlanToWorkingTimeConverter>();
...
var mapped = Mapper.Map<IEnumerable<WorkingTime>>(workPlanDTO)