Search code examples
c#viewmodelautomapper

Creating a DateTime using AutoMapper


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


Solution

  • Mapper.CreateMap<enquiryListEntry, EnquiriesListViewModel>()
        .ForMember(dest => dest.flightDate, opt => opt.MapFrom(src => new DateTime(src.flightYear, src.flightMonth, src.flightDay)));
    

    Should do it.