如何将枚举映射到数据库 ID
本文关键字:数据库 ID 映射 枚举 | 更新日期: 2023-09-27 18:35:34
我有枚举:
public enum Days
{
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7
}
我使用此枚举将 int 作为 ID 的值插入到数据库中。但是,当我从数据库中检索值以显示天数名称而不是该数据库 ID 时,如何才能使用该数据库 ID "映射"enum Days
?
有一个显示的数据列表,目前我显示了 DayId 和 ID,但是我如何映射此 ID 以显示枚举文本(星期一、星期二,...)而不是 ID(1,2,3..) ?
你真的不需要任何特别的东西,你可以从一个数据库中得到的整数强制转换为你的枚举:
int valueFromDB = 4;
Days enumValue = (Days)valueFromDB;
我不建议这种方法。 您需要几天的查找表。 例如
create table Days(
DaysID INT PRIMARY KEY,
Name VARCHAR(20))
所有其他表将具有 DaysID 的外键列。 我之所以建议反对你的方法,是因为你将自己限制在可能改变的硬编码值上。
如果需要,您可以将 Days 表加载到List<KeyValuePair<int, string>>
中。 如果您保持原样,则查看数据库的人不会知道 DaysID 1、2、3、4 等表示的方式。
我希望这有所帮助。
请尝试
以下操作。
//Let's say you following ids from the database
List<int> lstFromDB = new List<int>() { 1, 2, 3 };
List<string> result = (from int l in lst
select ((Days)l).ToString()
).ToList();
您可以使用以下扩展方法Enum.ToObject(typeof(Days), item)
对您有所帮助。
private List<string> ConvertIntToString(Enum days, params int[] daysIds)
{
List<string> stringList = new List<string>();
foreach (var item in daysIds)
{
stringList.Add(Enum.ToObject(days.GetType(), item).ToString());
}
return stringList;
}
按如下方式使用:
ConvertIntToString(new Days(),2, 4, 6, 1);
或
private List<Enum> ConvertIntToString(params int[] daysIds)
{
List<Enum> EnumList = new List<Enum>();
foreach (var item in daysIds)
{
EnumList.Add((Days)item);
}
return EnumList;
}
使用以下扩展方法来表达您的枚举
/// <summary>
/// Get the whilespace separated values of an enum
/// </summary>
/// <param name="en"></param>
/// <returns></returns>
public static string ToEnumWordify(this Enum en)
{
Type type = en.GetType();
MemberInfo[] memInfo = type.GetMember(en.ToString());
string pascalCaseString = memInfo[0].Name;
Regex r = new Regex("(?<=[a-z])(?<x>[A-Z])|(?<=.)(?<x>[A-Z])(?=[a-z])");
return r.Replace(pascalCaseString, " ${x}");
}
或者你可以提供描述来枚举它,使用下面
public enum Manufacturer
{
[Description("I did")]
Idid = 1,
[Description("Another company or person")]
AnotherCompanyOrPerson = 2
}
/// <summary>
/// Get the enum description value
/// </summary>
/// <param name="en"></param>
/// <returns></returns>
public static string ToEnumDescription(this Enum en) //ext method
{
Type type = en.GetType();
MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
return ((DescriptionAttribute)attrs[0]).Description;
}
return en.ToString();
}