Reputation: 6790
I'm trying to conditionally map two objects based on ExtendedField.type
. So if the type is textbox
then I would map to the TextBox
class, but if it's checkbox
then I would map to Checkbox
class. And of course this needs to be open for extension to map to other IHtmlElement derived types.
Mapper.Map<IEnumerable<ExtendedField, IEnumerable<IHtmlElement>>(extendedFields);
A sample of the objects:
public class ExtendedField {
public string type { get; set; }
public string prompt { get; set; }
public string value { get; set; }
}
public Interface IHtmlElement {
string label { get; set; }
string type { get; set; }
string value { get; set; }
}
public class TextBox : IHtmlElement {
public string label { get; set; }
public string type { get { return "textbox"; } }
public string value { get; set; }
}
public class CheckBox : IHtmlElement {
public string label { get; set; }
public string type { get { return "checkbox"; } }
public string value { get; set; }
}
I have created the mapping to map to IHtmlElement
but I can't think of how to dynamically tell AutoMapper which concrete class to map to based off the type
property.
Mapper.CreateMap<ExtendedField, IHtmlElement>()
.ForMember(dest => dest.label, opt => opt.MapFrom(src => src.prompt))
.ForMember(dest => dest.type, opt => opt.MapFrom(src => src.type))
.ForMember(dest => dest.value, opt => opt.MapFrom(src => src.extendedFieldValue));
Upvotes: 0
Views: 1194
Reputation: 106
in ExtendedField.type you must contain full qualified type name. write type converter:
public class ExtFieldToIHtmlElementConverter : TypeConverter<ExtendedField, IHtmlElement>
{
protected override IHtmlElement ConvertCore(ExtendedField source)
{
var obj = Activator.CreateInstance(Type.GetType(source.type)) as IHtmlElement;
obj.label = source.prompt;
obj.value = source.value;
return obj;
}
}
mapping:
mapper.CreateMap<ExtendedField, IHtmlElement>().ConvertUsing<ExtFieldToIHtmlElementConverter>();
example of using:
var element = Mapper.Map<IHtmlElement>(extFieldObj); // become instance that implement IHtmlElement interface.
Upvotes: 2