Creating a DateTime Using AutoMapper

I am trying to create a DateTime object from (year, month, day) which is returned from the database. I'm new to AutoMapper, so the push in the right direction will be great.

Here is the ViewModel containing the DateTime object, and the three values ​​you need to use 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 build FlightDate from the other three values. I tried various approaches, some of which did not even compile!

Like this:

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

Waiting for your answers.

M

+5
source share
3 answers
 Mapper.CreateMap<enquiryListEntry, EnquiriesListViewModel>() .ForMember(dest => dest.flightDate, opt.MapFrom(src => new DateTime(src.flightYear, src.flightMonth, src.flightDay))); 

Must do it.

+6
source
 Mapper.CreateMap<enquiryListEntry, EnquiriesListViewModel>() .ForMember(dest => dest.flightDate, opt => opt.Ignore); var result = Mapper.Map<enquiryListEntry, EnquiriesListViewModel>(yourBaseObject); result.flightDate = new DateTime(); 

After defining the mapping, you can run the Map method, you get your target object, then you can pass any value to your flightDate property.

0
source

This solution comes too late, but it's 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))); 
0
source

All Articles