Iterate recursively over object properties

I want to get all the properties of an object at runtime and save it in the database along with my values. I do this recursively, that is, whenever a property is also on an 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 that I create a new instance for the property objects (see emphasis), thereby losing all the data that was on the original object. How can I recursively iterate over all properties of an object? Is it possible?

Please, help. Thanks in advance.

+3
source share
1 answer

Use this instead to replace the highlighted line:

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

- , , GetValue() :

object v = propertyInfo.CanRead ?  propertyInfo.GetValue (entity, null) : null;
if (v != null) {
   if (...) {
   } else {
      SaveProperties (v);
   }
}
+5

Source: https://habr.com/ru/post/1771231/


All Articles