feat: 增加字符串转枚举转化器

This commit is contained in:
Argo-Tianyi 2021-12-12 18:58:04 +08:00
parent 4260dd6888
commit 5bc293dd50
1 changed files with 59 additions and 0 deletions

View File

@ -0,0 +1,59 @@
namespace BootstrapAdmin.DataAccess.PetaPoco.Coverters
{
/// <summary>
/// 字符串转枚举转换器
/// </summary>
public class StringToEnumConverter
{
private Type TargetType { get; set; }
/// <summary>
///
/// </summary>
/// <param name="targetType"></param>
public StringToEnumConverter(Type targetType) => TargetType = targetType;
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
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;
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
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;
}
}
}