Reputation: 4158
I have the following models:
public class BaseEntity
{
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
}
public class Child1 : BaseEntity { }
public class Child2 : BaseEntity { }
Dates are written into my database in UTC, but when I pull them out into viewmodels, I want the dates to be displayed in local time. So this is what I tried:
Mapper.CreateMap<BaseEntity, BaseViewModel>()
.ForMember(e => e.CreatedDate, b => b.MapFrom(x => DateHelper.ConvertToLocalTimeZone(x.CreatedDate)))
.ForMember(e => e.ModifiedDate, b => b.MapFrom(x => DateHelper.ConvertToLocalTimeZone(x.ModifiedDate)));
This does not work. It only works when I create the map explicitly for the child classes, like this, which I hardly think is reasonable to have to do:
Mapper.CreateMap<Child1, Child1ViewModel>()
.ForMember(e => e.CreatedDate, b => b.MapFrom(x => DateHelper.ConvertToLocalTimeZone(x.CreatedDate)))
.ForMember(e => e.ModifiedDate, b => b.MapFrom(x => DateHelper.ConvertToLocalTimeZone(x.ModifiedDate)));
I did some searching, but didn't find a solution that seemed to handle the custom mapping at the base class.
Thanks in advance.
Upvotes: 0
Views: 220
Reputation: 26765
Display logic like this should be done in your views, not in your view models. Keep your view models as DateTime, and then depending on your view technology you can create templated helpers or HtmlHelper extensions to standardize on how dates are displayed.
Upvotes: 1