Try to update a specific property of my model with Reflection. This works for all other types of my model except properties of type DateTime?
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 is thrown on the Convert.ChangeType part:
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 it working with Daniel A. White 's solution
Code updated (probably needs some finetuning, 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();
}
DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false. DateTime is a "Value Type". Basically a "value type" can't set to NULL. But by making them to "Nullable" type, We can set to null.
The Nullable < T > structure is using a value type as a nullable type. By default DateTime is not nullable because it is a Value Type, using the nullable operator introduced in C# 2, you can achieve this. Using a question mark (?) after the type or using the generic style Nullable.
Yes. If you have a nullable datetime column, then its fine.
Try to replace
Convert.ChangeType(value, propertyInfo.PropertyType)
by
Convert.ChangeType(value, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType)
(Not tested)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With