Automapper map to nullable DateTime property

核能气质少年 提交于 2020-12-26 07:47:46

问题


using Automapper 3.1.1 I can not compile this map:

Mapper.CreateMap<Domain.DomainObjects.Entities.Patient, PatientDto>()
                .ForMember(x => x.Deleted, opt => opt.MapFrom(input => input.Deleted.HasValue ? 
                    new DateTime(input.Deleted.Value.Ticks, DateTimeKind.Utc) : null ));

Error:

Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'DateTime'

Entity:

public class Patient : Entity
{
        // more properties
        public virtual DateTime? Deleted { get; set; }
}

Feel like I am missing something obvious but can not figure out what exactly.

note: Dto contains DateTime? Deleted too


回答1:


I haven't tested, but you should just need to explicitly cast null to a DateTime?. ((DateTime?)null)

Mapper.CreateMap<Domain.DomainObjects.Entities.Patient, PatientDto>()
                .ForMember(x => x.Deleted, opt => opt.MapFrom(input => input.Deleted == null ? (DateTime?)null : (
                new DateTime(input.Deleted.Value.Ticks, DateTimeKind.Utc))));



回答2:


Just cast the new DateTime to DateTime?:

Mapper.CreateMap<Domain.DomainObjects.Entities.Patient, PatientDto>()
            .ForMember(x => x.Deleted, opt => opt.MapFrom(input => input.Deleted.HasValue ? 
                (DateTime?) new DateTime(input.Deleted.Value.Ticks, DateTimeKind.Utc) : null ));


来源:https://stackoverflow.com/questions/48551696/automapper-map-to-nullable-datetime-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!