AutoMapper 自定义类型转换器的问题

问题描述 投票:0回答:1

我尝试使用自动映射器创建自定义类型转换器,但我无法开始工作 - 甚至无法编译。

这是我的自定义转换器:

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));
    }
}

我正在尝试像这样连接它:

  CreateMap<TPWorkPlanDTO, List<WorkingTime>>()
   .ConvertUsing<WorkPlanToWorkingTimeConverter>();

但我收到此错误:

类型“Mapping.Converter.WorkPlanToWorkingTimeListConverter”不能用作泛型类型或方法“IMappingExpressionBase>.ConvertUsing()”中的类型参数“TTypeConverter”。没有从“Mapping.Converter.WorkPlanToWorkingTimeListConverter”到“AutoMapper.ITypeConverter>”的隐式引用转换。

我尝试了一些

ConvertUsing()
获取类型的重载,但我就是无法编译它。

在下面我附上了我的 DTO 和我需要映射的模型:

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; }
}
c# automapper
1个回答
0
投票

WorkPlanToWorkingTimeListConverter : ITypeConverter<TPWorkPlanDTO, IEnumerable<WorkingTime>>
定义到
IEnumarable<...>
的映射。由于泛型类型
T1<T2, IEnumerable<T3>>
T1<T2, List<T3>>
不同,因此需要将此转换器用作到
IEnumerable<...>
的映射,而不是到
List<...>
:

CreateMap<TPWorkPlanDTO, IEnumerable<WorkingTime>>()
   .ConvertUsing<WorkPlanToWorkingTimeConverter>();
© www.soinside.com 2019 - 2024. All rights reserved.