-
Notifications
You must be signed in to change notification settings - Fork 112
Custom mapping
Sergey Morenko edited this page Apr 12, 2015
·
3 revisions
TinyMapper
supports TypeConverter
The sample shows how to map SourceClass
to TargetClass
:
public class TargetClass
{
public string FullName { get; set; }
}
public class SourceClass
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public sealed class SourceClassConverter : TypeConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(TargetClass);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
var concreteValue = (SourceClass)value;
var result = new TargetClass
{
FullName = string.Format("{0} {1}", concreteValue.FirstName, concreteValue.LastName)
};
return result;
}
}
Here's additional sample
Thru attribute
[TypeConverter(typeof(SourceClassConverter))]
public class SourceClass
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
or code
TypeDescriptor.AddAttributes(typeof(SourceClass), new TypeConverterAttribute(typeof(SourceClassConverter)));
TinyMapper.Bind<SourceClass, TargetClass>();
var source = new SourceClass
{
FirstName = "John",
LastName = "Doe"
};
var result = TinyMapper.Map<TargetClass>(source);