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 {
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.
source
share