From 5bc293dd50b58d370a13280bb418dd3979db3266 Mon Sep 17 00:00:00 2001 From: Argo-Tianyi Date: Sun, 12 Dec 2021 18:58:04 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2=E8=BD=AC=E6=9E=9A=E4=B8=BE=E8=BD=AC=E5=8C=96=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Coverters/StringToEnumConverter.cs | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/blazor/admin/BootstrapAdmin.DataAccess.PetaPoco/Coverters/StringToEnumConverter.cs diff --git a/src/blazor/admin/BootstrapAdmin.DataAccess.PetaPoco/Coverters/StringToEnumConverter.cs b/src/blazor/admin/BootstrapAdmin.DataAccess.PetaPoco/Coverters/StringToEnumConverter.cs new file mode 100644 index 00000000..53069a97 --- /dev/null +++ b/src/blazor/admin/BootstrapAdmin.DataAccess.PetaPoco/Coverters/StringToEnumConverter.cs @@ -0,0 +1,59 @@ +namespace BootstrapAdmin.DataAccess.PetaPoco.Coverters +{ + /// + /// 字符串转枚举转换器 + /// + public class StringToEnumConverter + { + private Type TargetType { get; set; } + + /// + /// + /// + /// + public StringToEnumConverter(Type targetType) => TargetType = targetType; + + /// + /// + /// + /// + /// + /// + public object? ConvertFromDb(object value) + { + if (value == null) throw new ArgumentNullException(nameof(value)); + + object? ret; + if (value != null && Enum.TryParse(TargetType, value.ToString(), true, out var v)) + { + ret = v; + } + else + { + throw new InvalidCastException($"{value} 无法转化为 {TargetType.Name} 成员"); + } + return ret; + } + + /// + /// + /// + /// + /// + /// + public object ConvertToDb(object value) + { + object? ret; + var field = value?.ToString(); + if (!string.IsNullOrEmpty(field) && Enum.IsDefined(TargetType, field)) + { + ret = field; + } + else + { + ret = Enum.GetNames(TargetType).First(); + } + return ret; + } + } +}