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.