My question is, what is the best way I can map one object to another in the most maintainable manner. I cannot change the way the Dto object that we are getting is setup to
This is a possible generic implementation using a bit of reflection (pseudo-code, don't have VS now):
public class DtoMapper
{
Dictionary properties;
public DtoMapper()
{
// Cache property infos
var t = typeof(DtoType);
properties = t.GetProperties().ToDictionary(p => p.Name, p => p);
}
public DtoType Map(Dto dto)
{
var instance = Activator.CreateInstance(typeOf(DtoType));
foreach(var p in properties)
{
p.SetProperty(
instance,
Convert.Type(
p.PropertyType,
dto.Items[Array.IndexOf(dto.ItemsNames, p.Name)]);
return instance;
}
}
Usage:
var mapper = new DtoMapper();
var modelInstance = mapper.Map(dto);
This will be slow when you create the mapper instance but much faster later.