开发者

Null/MinValue check in Automapper configuration

I'm pulling a list of customers left join appointments. Since all customers may not have appointments, based on this answer, I have the following Automapper configuration:

Mapper.CreateMap<Event, EventDetailsViewModel>()
               .ForMember(dest => dest.StartDateTime, opt => opt.MapFrom(
                       src => src.StartDateTime == DateTime.M开发者_开发百科inValue ? "" : DateTimeHelper.ConvertFromUtc(src.StartDateTime, src.TimeZoneId)
                           .ToString("MM/dd/yyyy hh:mm tt", System.Globalization.CultureInfo.InvariantCulture)))
               .ForMember(dest => dest.EndDateTime, opt => opt.MapFrom(
                       src => src.StartDateTime == DateTime.MinValue ? "" : DateTimeHelper.ConvertFromUtc(src.EndDateTime, src.TimeZoneId)
                           .ToString("MM/dd/yyyy hh:mm tt", System.Globalization.CultureInfo.InvariantCulture)))
               .IgnoreAllNonExisting();

And the DateTimeHelper is straightforward:

    public static class DateTimeHelper
    {
        public static DateTime ConvertToUtc(DateTime thisDate, string timeZoneId)
        {
            return TimeZoneInfo.ConvertTimeToUtc(thisDate, TimeZoneInfo.FindSystemTimeZoneById(timeZoneId));
        }

        public static DateTime ConvertFromUtc(DateTime thisDate, string timeZoneId)
        {
            return TimeZoneInfo.ConvertTimeFromUtc(thisDate, TimeZoneInfo.FindSystemTimeZoneById(timeZoneId));
        }
    }

I verified that the StartDateTime is '1/1/0001 12:00:00 AM', but somehow the check for DateTime.MinValue isn't working and it gets over to the DateTimeHelper which of course then throws an exception.

What am I missing?


In case any one is interested, I finally implemented a workaround in place:

public static DateTime ConvertFromUtc(DateTime thisDate, string timeZoneId)
{
   if (!String.IsNullOrEmpty(timeZoneId)) // workaround
      return TimeZoneInfo.ConvertTimeFromUtc(thisDate, TimeZoneInfo.FindSystemTimeZoneById(timeZoneId));

   return thisDate;
}

Not ideal, but does the job and I can move on.


Based on the code above, your destination property: "StartDateTime" is a string.

I just put the code into a watch window, and here is what you get:

Your comparison

Name:  "1/1/0001 12:00:00 AM" == DateTime.MinValue  
Value: Operator '==' cannot be applied to operands of type 'string' and 'System.DateTime'

My comparison

Name:  "1/1/0001 12:00:00 AM" == DateTime.MinValue.ToString()   
Value: true 
Type:  bool
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜