Field Conversion

Aug 26, 2010 at 5:15 PM

This may be usefull to others:

    // An improved version of this would allow for setting mapping pairs e.g. 1 to 3, 4 to 1, etc.
    // Another variation of this would match on field names, making conversion completely automatic
    public class FieldToFieldMapper : ValueInjection
    {
        private static object ChangeTypeTo(Type underlyingType, object value)
        {
            if (value == null)
                return null;

            if (underlyingType == null)
                throw new ArgumentNullException("value");

            if (underlyingType.IsGenericType && underlyingType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                var converter = new NullableConverter(underlyingType);
                underlyingType = converter.UnderlyingType;
            }

            // Guid convert
            if (underlyingType == typeof(Guid))
            {
                return new Guid(value.ToString());
            }

            // Do conversion
            return underlyingType.IsAssignableFrom(value.GetType()) ?
                  Convert.ChangeType(value, underlyingType)
                : Convert.ChangeType(value.ToString(), underlyingType);
        }

        protected override void Inject(object source, object target)
        {
            var sprops = source.GetProps();
            var tprops = target.GetProps();

            for (int i = 0; i < tprops.Count; i++)
            {
                if (i > sprops.Count)
                    break;

                var cnvVal = ChangeTypeTo(tprops[i].PropertyType, sprops[i].GetValue(source));

                tprops[i].SetValue(target, cnvVal);
            }
        }
    }