When working in an n-tier environment it can be a really big pain to convert between data contracts and business objects. Luckily, the System.Reflection namespace can make this a little less painful. Here’s a chunk of code that can help with this process:
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!

Advertisements