64 lines
1.6 KiB
C#
Raw Normal View History

using LMS.Common.Enums;
2024-10-18 12:44:12 +08:00
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;
namespace LMS.Repository.DB;
public class Options
{
[Key]
public required string Key { get; set; } = string.Empty;
/// <summary>
/// Value of the option这个值是一个json字符串
/// </summary>
public string? Value { get; set; } = string.Empty;
public OptionTypeEnum Type { get; set; } = OptionTypeEnum.String;
// 写一个字段映射Value判断是不是json字符串是的话就解析成对象
// 写一个字段映射Value判断是不是json字符串是的话就解析成对象
public T? GetValueObject<T>()
2024-10-18 12:44:12 +08:00
{
if (string.IsNullOrEmpty(Value))
2024-10-18 12:44:12 +08:00
{
return default;
}
2024-10-18 12:44:12 +08:00
if (Type == OptionTypeEnum.JSON)
{
return JsonConvert.DeserializeObject<T>(Value ?? "{}");
}
2024-10-18 12:44:12 +08:00
if (Type == OptionTypeEnum.Number)
{
if (double.TryParse(Value, out double result))
2024-10-18 12:44:12 +08:00
{
return (T)Convert.ChangeType(result, typeof(T));
2024-10-18 12:44:12 +08:00
}
return default;
2024-10-18 12:44:12 +08:00
}
return (T)Convert.ChangeType(Value, typeof(T));
}
// 写一个方法设置Value的值
public void SetValueObject<T>(T value)
{
if (value == null)
2024-10-18 12:44:12 +08:00
{
Value = string.Empty;
return;
}
2024-10-18 12:44:12 +08:00
if (Type == OptionTypeEnum.JSON)
{
Value = JsonConvert.SerializeObject(value);
}
else
{
Value = value.ToString();
2024-10-18 12:44:12 +08:00
}
}
}