How to use automapper with convertusing and a condition?

Viewed 3788

We are using automapper in .net core to map viewmodels to dtos. For datetime we would like to save utc to our database, but for the user we would like to display local timezone. This goes well with a ConvertUsing like this:

CreateMap<CreateAgendaItemViewModel, AgendaItemDto>()
.ForMember(dest => dest.StartDateTime, opt => opt.ConvertUsing(new ToUtcTimeConverter()))
.ReverseMap()
.ForMember(dest => dest.StartDateTime, opt => opt.ConvertUsing(new ToLocalTimeConverter()))

So far so good if you always want to change the time. However it is possible that only a date is set and not a time (because it is an all day event) and we would like to keep the time as is like this: 2020-04-09 00:00:00.0000000. We have a boolean in the models that indicates if it is indeed an all day event or not. How can we condition the convertusing?

We already tried MapFrom with condition, but it cannot have a convertusing. We also tried this, but it ended up not being mapped, or being mapped to utc time.

.ForMember(dest => dest.StartDateTime, opt => { opt.Condition(src => !src.AllDayEvent); opt.ConvertUsing(new ToUtcTimeConverter()); })
1 Answers

Thanks for the possible solutions in the comments. I tried the custom valueconvert, however I ended up with a lot of classes for each type of convert, while we have multiple sources and destinations that request the same solution. That is not what I wanted. But I also found out that convertUsing with a condition was not the way to go for this problem. This is how I solved the check and the mapping:

 CreateMap<AgendaItemViewModel, AgendaItemDto>()
.ForMember(dest => dest.StartDateTime, opt => opt.MapFrom(src => src.AllDayEvent ? src.StartDateTime : src.StartDateTime.ToUniversalTime()))
.ReverseMap()
.ForMember(dest => dest.StartDateTime, opt => opt.MapFrom(src => src.AllDayEvent ? src.StartDateTime : src.StartDateTime.ToLocalTimeZoneTime()))

So ToUniversalTimeZone is DateTime extension and I created our own ToLocalTimeZoneTime extension.

Related