diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Reflection/TypeHelper.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Reflection/TypeHelper.cs index 8a67d20b31..0118fd9874 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Reflection/TypeHelper.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Reflection/TypeHelper.cs @@ -80,6 +80,37 @@ public static class TypeHelper return false; } + public static TProperty? ChangeTypePrimitiveExtended(object? value) + { + if (value == null) + { + return default; + } + + if (IsPrimitiveExtended(typeof(TProperty), includeEnums: true)) + { + var conversionType = typeof(TProperty); + if (IsNullable(conversionType)) + { + conversionType = conversionType.GetFirstGenericArgumentIfNullable(); + } + + if (conversionType == typeof(Guid)) + { + return (TProperty)TypeDescriptor.GetConverter(conversionType).ConvertFromInvariantString(value.ToString()!)!; + } + + if (conversionType.IsEnum) + { + return (TProperty)Enum.Parse(conversionType, value.ToString()!); + } + + return (TProperty)Convert.ChangeType(value, conversionType, CultureInfo.InvariantCulture); + } + + throw new AbpException("ChangeTypePrimitiveExtended does not support non-primitive types. Use non-generic GetProperty method and handle type casting manually."); + } + public static bool IsNullable(Type type) { return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); diff --git a/framework/src/Volo.Abp.ObjectExtending/Volo/Abp/Data/HasExtraPropertiesExtensions.cs b/framework/src/Volo.Abp.ObjectExtending/Volo/Abp/Data/HasExtraPropertiesExtensions.cs index 75f5672a29..54cdc2bc94 100644 --- a/framework/src/Volo.Abp.ObjectExtending/Volo/Abp/Data/HasExtraPropertiesExtensions.cs +++ b/framework/src/Volo.Abp.ObjectExtending/Volo/Abp/Data/HasExtraPropertiesExtensions.cs @@ -26,34 +26,9 @@ public static class HasExtraPropertiesExtensions public static TProperty? GetProperty(this IHasExtraProperties source, string name, TProperty? defaultValue = default) { - var value = source.GetProperty(name); - if (value == null) - { - return defaultValue; - } - - if (TypeHelper.IsPrimitiveExtended(typeof(TProperty), includeEnums: true)) - { - var conversionType = typeof(TProperty); - if (TypeHelper.IsNullable(conversionType)) - { - conversionType = conversionType.GetFirstGenericArgumentIfNullable(); - } - - if (conversionType == typeof(Guid)) - { - return (TProperty)TypeDescriptor.GetConverter(conversionType).ConvertFromInvariantString(value.ToString()!)!; - } - - if (conversionType.IsEnum) - { - return (TProperty)Enum.Parse(conversionType, value.ToString()!); - } - - return (TProperty)Convert.ChangeType(value, conversionType, CultureInfo.InvariantCulture); - } - - throw new AbpException("GetProperty does not support non-primitive types. Use non-generic GetProperty method and handle type casting manually."); + return TypeHelper.ChangeTypePrimitiveExtended( + source.GetProperty(name, (object?) defaultValue) + ) ?? defaultValue; } public static TSource SetProperty(