Set the property value for NULL time

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();
}
+4
source share
2 answers

Try replacing

Convert.ChangeType(value, propertyInfo.PropertyType)

by

Convert.ChangeType(value, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType)

(not verified)

+5
source

Try converting the value to DateTime: DateTime.Parse (value);

0
source

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


All Articles