Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper map to nullable DateTime property

Tags:

c#

automapper

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

like image 206
pandemic Avatar asked Jan 03 '23 21:01

pandemic


2 Answers

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))));
like image 68
ps2goat Avatar answered Jan 11 '23 17:01

ps2goat


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 ));
like image 25
YuvShap Avatar answered Jan 11 '23 18:01

YuvShap