Our supplier's webservice is returning address objects (~30 fields) and I'm using LINQ and reflection to store the returned data straight into the databse. I loop over the attributes and set the value from the object to the LINQ class.
I'm fairly new to refection and I'm worried this may be bad practice; it saves ~30 lines of code in 3 or 4 methods but I'm afraid it could introduce hard to fix bugs.
EDIT Here is the code. Target is normally a LINQ to SQL entity and input would be a webservice object.
public static void SetValues(object target, object input)
{
Type targetType = target.GetType();
Type inputType = input.GetType();
PropertyDescriptorCollection inputProperties = TypeDescriptor.GetProperties(inputType);
PropertyDescriptorCollection targetProperties = TypeDescriptor.GetProperties(targetType);
foreach (PropertyDescriptor p in inputProperties)
{
object value = p.GetValue(input);
var t = targetProperties.Find(p.Name, false);
if (t != null && value != null)
{
if (value.GetType() == typeof(string) || value.GetType() == typeof(Int64) || value.GetType() == typeof(int) || value.GetType() == typeof(Boolean))
{
t.SetValue(target, value);
}
else if (value.GetType() == typeof(DateTime) || value.GetType() == typeof(DateTime?))
{
if ((DateTime)value > DateTime.MinValue)
{
t.SetValue(target, value);
}
}
else
{
t.SetValue(target, value.ToString());
}
}
}