Created
December 14, 2023 19:55
-
-
Save jamescurran/2579061be5b5e74257aae8eb5068f26e to your computer and use it in GitHub Desktop.
Update an Object using a dictionary with the properties to change
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public static void UpdateFromText<T>(this T target, IDictionary<string, object> changes) | |
| where T : class | |
| { | |
| foreach (var kvp in changes) | |
| { | |
| var propsTarget = typeof(T).GetProperty(kvp.Key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); | |
| if (propsTarget == null) | |
| //throw new ArgumentOutOfRangeException(nameof(changes), $"{kvp.Key} is not a property of the target"); | |
| continue; | |
| try | |
| { | |
| var newVal = kvp.Value; | |
| var newStr = newVal as string; | |
| if (newStr == "null" || newVal == null) | |
| { | |
| if (propsTarget.PropertyType.IsClass || IsNullable(propsTarget)) | |
| propsTarget.SetValue(target, null); | |
| } | |
| else | |
| { | |
| var targetType = IsNullable(propsTarget) | |
| ? propsTarget.PropertyType.GenericTypeArguments[0] | |
| : propsTarget.PropertyType; | |
| if (targetType == typeof(bool)) | |
| { | |
| char chr = Char.ToUpperInvariant(newStr[0]); | |
| if (chr == 'Y') | |
| { | |
| propsTarget.SetValue(target, true); | |
| continue; | |
| } | |
| else if (chr == 'N') | |
| { | |
| propsTarget.SetValue(target, false); | |
| continue; | |
| } | |
| } | |
| object value = Convert.ChangeType(newVal, targetType); | |
| propsTarget.SetValue(target, value); | |
| } | |
| } | |
| catch (Exception ex) | |
| { | |
| throw new ArgumentOutOfRangeException( | |
| $"{kvp.Value} is not assignable to {propsTarget.PropertyType.Name} (Property {kvp.Key})", ex); | |
| } | |
| } | |
| } | |
| public static bool IsNullable(PropertyInfo type) => | |
| type.PropertyType.IsConstructedGenericType && type.PropertyType.Name == "Nullable`1"; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment