问题
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