Wednesday, 2 May 2012

C# reflection based simple ObjectMapper

public class ObjectMapper
{
    public static object Map(object from, Func<PropertyInfo, bool> ignore)
    {
        return Map(from, null, ignore);
    }
    public static object Map(object from, object to, Func<PropertyInfo, bool> ignore)
    {
        if(from==null) throw new ArgumentException("NULL value","from");
        if (to == null)
        {
            to = Activator.CreateInstance(from.GetType());
        }
        Type type = from.GetType();
        var properties = type.GetProperties();
        foreach (var property in properties)
        {
            if (ignore==null || !ignore(property))
            {
                if(property.GetSetMethod()!=null)
                    property.SetValue(to, property.GetValue(from, null), null);
            }
        }
        return to;
    }
}
And an example of ignore method implementation to not map properties annotated with Association attribute (from Linq2Sql)
public static bool IgnoreAssociations(PropertyInfo property)
{
    if (Attribute.GetCustomAttribute(property, typeof(AssociationAttribute)) != null)
    {
        return true;
    }
    return false;
}

No comments:

Post a Comment