I have a formatter
public class ColorFormatter : IValueFormatter
{
public string FormatValue(ResolutionContext context)
{
return "green"
}
}
Mapper.CreateMap<MyClass, MyViewModel>().ForMember(dest => dest.color, opt => opt.AddFormatter<ColorFormatter>());
MyClass has nothing called bgColor but MyViewModel does and I want all of the bgColors to have “green”.
So why is it not being triggered?
Everything else in MYClass gets successfully mapped to MyViewModel.
List<MyViewModel> vm = Mapper.Map<List<MyClass>, List<MyViewModel>>(myClasses);
[Serializable]
public class MyClass
{
public virtual int Id { get; private set; }
public virtual string Title { get; set; }
public virtual DateTime Start { get; set; }
public virtual DateTime End { get; set; }
public virtual string Description { get; set; }
public virtual string Where { get; set; }
public virtual bool AllDay { get; set; }
public virtual AnotherClass AnotherClass { get; set; }
public virtual int RepeatingId { get; set; }
}
public class MyViewModel
{
public int id { get; set; }
public string title { get; set; }
public bool allDay { get; set; }
public string start { get; set; }
public string end { get; set; }
public string color { get; set; }
public string appointmentId { get; set; }
public string textColor { get; set; }
}
The ValueFormatter is only applied when it has a source value to format. If you add a Color property onto the MyClass class then you will see the color “green” get applied. I’m not sure if this is an AutoMapper bug as it would normally complain if there is no source value to map from. I’m guessing that it assumes when you apply .ForMember() then it can no longer automatically check these things and it is relying on you to ensure that the mapping is correct. Rather than using a ValueFormatter, use a ValueResolver that returns a string like this: