Home > OS >  Override Automapper TypeConverter
Override Automapper TypeConverter

Time:11-01

I have created an Automapper 12 TypeConverter for <DateTime, DateTime> that converts the source DateTime to UTC and removes the time portion of the DateTime object so that we store just the Date portion in the database.

this.CreateMap<DateTime, DateTime>().ConvertUsing(new DateTimeConverterForUniversalTime());

public class DateTimeConverterForUniversalTime : ITypeConverter<DateTime, DateTime>
{
  public DateTime Convert(DateTime source, DateTime destination, ResolutionContext context)
  {
    
    var convertedSource = new DateTime(source.Ticks, DateTimeKind.Utc);
    return convertedSource.Date;
  }
}

However, I have 1 class where I still want the time portion of its DateTime property. How can I override the type converter for this one property on one class? I still want to convert it to UTC before storing it in the database (or convert to local time on the way back out), but I don't want the time portion being removed.

I found this post, but I DO NOT want to write an <object, object> converter that is then being run for every conversion, just to check if this one field on one class is being converted.

CodePudding user response:

Instead of a map you can use a value transformer. The advantage is that they're more flexible about where they apply. A map is always global, it applies everywhere.

  • Related