Try updating a specific property of my model with Reflection. Does this work for all other types of my model except for properties of type DateTime?
the code:
public void UpdateProperty(Guid topicGuid, string property, string value)
{
var topic = Read(topicGuid);
PropertyInfo propertyInfo = topic.GetType().GetProperty(property);
propertyInfo.SetValue(topic, Convert.ChangeType(value, propertyInfo.PropertyType), null);
topic.DateModified = DateTime.Now;
Save();
}
The following error occurs in Convert.ChangeType :
Invalid cast from 'System.String' to 'System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'
How can this be solved?
Update
Got a job with Daniel A. White solution
The code is updated (maybe some kind of finale is needed, but it works):
public void UpdateProperty(Guid topicGuid, string property, string value)
{
var topic = Read(topicGuid);
PropertyInfo propertyInfo = topic.GetType().GetProperty(property);
object changedType = propertyInfo.PropertyType == typeof(DateTime) || propertyInfo.PropertyType == typeof(DateTime?)
? DateTime.Parse(value)
: Convert.ChangeType(value, propertyInfo.PropertyType);
propertyInfo.SetValue(topic, changedType, null);
topic.DateModified = DateTime.Now;
Save();
}
source
share