Automapper-map long to DateTime c#

时间:2017-07-21 12:18:56

标签: c# automapper

是否可以将类型long映射到类型DateTime?我有两个不同领域的课程:

头等舱:

public class Task
{    
    public int id_task { get; set; }    
    public string state{ get; set; }    
    public long date_prev { get; set; }    
    public long date_last { get; set; }
}

第二课:

public class TaskDTO
{    
    public int id_task { get; set; }    
    public string state{ get; set; }    
    public DateTime date_prev { get; set; }    
    public DateTime date_last { get; set; }
}

我想将第一堂课映射到第二堂课:

public HttpResponseMessage PostTask(Task task)
{
    Mapper.Initialize(cfg =>
    {
        cfg.CreateMap<long, DateTime>().ConvertUsing(new DateTimeTypeConverter());
        cfg.CreateMap<Task, TaskDTO>()
            .ForMember(dest => dest.date_prev, opt => opt.MapFrom(src => new DateTime(task.date_prev)));
    });

    TaskDTO taskDTO = Mapper.Map<Task,TaskDTO>(task);

    /*...*/
}

但是,当我运行我的应用程序时,我收到AutoMapper错误:

  

&#34; ExceptionMessage&#34;:&#34;转换无效于&#39; Int64&#39;至   &#39; DateTime&#39;。&#34;,&#34; ExceptionType&#34;:&#34; System.InvalidCastException&#34;,

有什么想法吗?非常感谢!

1 个答案:

答案 0 :(得分:2)

定义映射long - &gt;使用自定义DateTime的{​​{1}}(正如您已经做过的那样):

ITypeConverter

请注意,如果来源为public class TicksToDateTimeConverter: ITypeConverter<long, DateTime> { public string Convert(long source, DateTime destination, ResolutionContext context) { return new DateTime(source); // interpret long as Ticks } } CreateMap<long, DateTime>().ConvertUsing<TicksToDateTimeConverter>(); 且目的地为long,则AutoMapper会自动应用此规则,因此DateTime的映射只是

TaskDTO