tags:

views:

75

answers:

1

I want to get all properties of an object during runtime and save it on a batabase together with its values. I am doing this recursively i.e. whenever a property is also on object, I will call the same method and pass the property as a parameter.

See my code below:

private void SaveProperties(object entity) {

    PropertyInfo[] propertyInfos = GetAllProperties(entity);
    Array.Sort(propertyInfos,
                delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
                { return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });

    _CurrentType = entity.GetType().Name;

    foreach (PropertyInfo propertyInfo in propertyInfos) {
        if (propertyInfo.GetValue(entity, null) != null) {
            if (propertyInfo.PropertyType.BaseType != typeof(BaseEntity)) {
                SaveProperty((BaseEntity)entity, propertyInfo);
            }
            else {
                // **here**
                SaveProperties(Activator.CreateInstance(propertyInfo.PropertyType));
            }
        }
    }
}

However, The problem with my current code is I create a new instance for property objects (see emphasis) thus losing all data that was on the original object. How can I recursively iterate on all the properties of an object? Is this possible?

Please help. Thanks in advance.

+3  A: 

Use this instead to replace your emphasized line:

SaveProperties (propertyInfo.GetValue (entity, null));

I would also do something like this to make sure GetValue() is applicable and to avoid multiple calls to it:

object v = propertyInfo.CanRead ?  propertyInfo.GetValue (entity, null) : null;
if (v != null) {
   if (...) {
   } else {
      SaveProperties (v);
   }
}
Gonzalo
It worked! Thanks man! I knew I was just missing something. Must be from too much coffee and too little hours of sleep.
third