Creating a DateTime using AutoMapper
Asked Answered
W

2

8

I am struggling to create a DateTime object from (year, month, day) which is being returned from the database. I am rather new to AutoMapper so a nudge in the right direction would be great.

Here is the ViewModel containing the DateTime object and the three values that need to be used to create the DateTime:

public class EnquiriesListViewModel
{
    // other field elided
    public sbyte flightDay;
    public sbyte flightMonth;
    public bool flightYear
    public DateTime flightDate;
    // other field elided
}

I would like AutoMapper to construct the flightDate from the other three values. I have tried various approaches, some of which didn't even compile!

Like this:

Mapper.CreateMap<enquiryListEntry, EnquiriesListViewModel>()
    .ForMember(dest => dest.flightDate,  /* what goes in here? */);

Looking forward to your responses.

M

Whoosh answered 27/4, 2015 at 11:42 Comment(1)
It would be helpful to see the definition of enquiryListEntry.Arrack
C
16
Mapper.CreateMap<enquiryListEntry, EnquiriesListViewModel>()
    .ForMember(dest => dest.flightDate, opt => opt.MapFrom(src => new DateTime(src.flightYear, src.flightMonth, src.flightDay)));

Should do it.

Carbone answered 27/4, 2015 at 11:47 Comment(1)
@Richard, that's right, just realized it when I submitted the answer. Edited it now.Carbone
E
1

This solution is coming too late but its good because it applies to .NET 4.6.1

Mapper.CreateMap<enquiryListEntry, EnquiriesListViewModel>()
      .ForMember(dest => dest.flightDate, 
                 opt => opt.AddTransform(src => new DateTime(src.Year,
                                                             src.Month,
                                                             src.Day)));
Electroencephalogram answered 8/3, 2018 at 18:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.