public class ContractConveter<U, V>
{
public static U Convert(V left)
{
if (left == null)
{
// The equivalent type for null is null, right?
return default(U);
}
U right = Activator.CreateInstance<U>();
PropertyInfo[] leftProperties = typeof(V).GetProperties();
PropertyInfo[] rightProperties = typeof(U).GetProperties();
// We will populate this with the equivalent properties.
var properties = new Dictionary<PropertyInfo, PropertyInfo>();
foreach (PropertyInfo leftProperty in leftProperties)
{
foreach (PropertyInfo rightProperty in rightProperties)
{
if (string.Equals(leftProperty.Name.ToLower(),
rightProperty.Name.ToLower()))
{
properties.Add(leftProperty, rightProperty);
}
}
}
// Now apply the properties on each side.
foreach (PropertyInfo leftProperty in properties.Keys)
{
PropertyInfo rightProperty = properties[leftProperty];
rightProperty.SetValue(right,
leftProperty.GetValue(left, null), null);
}
return (right);
}
}
There are valid arguments that, for instance, models shouldn’t expose any info about the DAL from which they came to the view. Or that your business objects shouldn’t explicitly be declared as data contracts.
Different people have different opinions on this. I, for one, am a very big proponent of strict separation of concerns so I like to minimize the amount of dependency-driven information available to each layer of my applications.
Traditionally, though, this has been hard — you have to write a lot of “left-hand/right-hand” code, as Scott Hanselman calls it, which is error prone and has terrible maintainability issues. This approach should be helpful.
Remember, though, when converting from a data contract to a business object you’ll likely need to hit your DAL once more to get a complete state for your object!
Hi, Your ClassConvert class seems to be exactly what I’m looking for to easily sync my DTO objects with my DataContract options when the properties are the same.
Sadly I’m not the best with generics and I’m not sure how to consume this class.
Would you be able to provide a simple example?
Cheers