Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 572
serlingpa Avatar asked Apr 27 '15 11:04

serlingpa


2 Answers

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

Should do it.

like image 176
Kevin D Avatar answered Sep 30 '22 20:09

Kevin D


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)));
like image 32
Boris Avatar answered Sep 30 '22 20:09

Boris