Label Cloud

Tuesday, July 15, 2008

Simple EntityMapperTranslator

CAB defines a very clean way of defining a translator for converting objects from one type to another. A typical use for this is to convert from an "wire" object a business object and back. This is done by creating an EntityMapperTranslator. Defining two methods: BusinessToService and ServiceToBusiness. And then registering the translator in the IEntityTranslatorService.

Often, the business object identical or nearly identical to the wire object. The code below will copy every property from the SourceType to the TargetType. Of course, this can be used outside of the EntityMapperTranslator as well for the same purpose.

class TypeTranslator : EntityMapperTranslator<SourceType, TargetType>
{
    protected override TargetType BusinessToService(IEntityTranslatorService service, SourceType value)
    {
        TargetType target = new TargetType();
        foreach (PropertyInfo pi in value.GetType().GetProperties())
        {
           PropertyInfo newPi = target.GetType().GetProperty(pi.Name);
           if (newPi != null)
           {
              if (service.CanTranslate(newPi.PropertyType, pi.PropertyType))
                 newPi.SetValue(target, service.Translate(newPi.PropertyType, pi.GetValue(value, null)), null);
              else
                 newPi.SetValue(target, pi.GetValue(value, null), null);
           }
        }
        return target;
    }
}


Share/Save/Bookmark