c# - 有没有办法使用单个字符获取枚举的字符串值?
问题描述
我在 MVC 应用程序中使用一个枚举,它看起来像下面的枚举,
public enum School
{
DVB=1,
AVD=2,
ASB=3
}
而且我从每所学校的数据库中获取了唯一的单个字符,例如:
D for DVB
A for AVD
B for ASB
我想打印枚举值的全名。我可以通过以下方式实现我的目标,即我可以编辑枚举并按字符替换枚举的整数值。但我认为这不是一个好的解决方案,因为现有代码也使用整数值。
有没有其他方法可以使用单个字符获取枚举的字符串值?
解决方案
最干净的方法是与您的团队坐在一起计划并接受迁移您的数据库并存储一个整数值。
无论如何,根据您在问题中的评论,您正在使用实体框架并将您的实体映射到视图模型。以下步骤可以帮助您无需反思,添加新属性或新枚举。
假设您正在使用一个名为 MyEntity
contains 的实体,该实体实际上包含一个名为 的属性MySchool
。
首先不是使用School
枚举作为类型MySchool
属性,而是使用字符串类型。因此 EF 只会从数据库中检索数据并将其直接放入属性中。无需转换。所以你会有这样的东西:
public class MyEntity
{
public string MySchool { get; set; }
}
其次,总是在你的MyEntity
类中添加另一个属性,让它命名MySchoolEnum
为枚举类型School
,而不是映射到数据库,这样你就有了:
[NotMapped] // <-- This tell EF that this property is not mapped to the database.
public School? MyShcoolEnum
{
get
{
// Getting the value of this property depends on the value of the database
// which is stored into MySchool property.
switch (MySchool)
{
case "D": return School.DVB;
case "A": return School.AVD;
case "B": return School.ASB;
default: return null;
}
}
set
{
// When setting this property
// you automatically update the value of MySchool property
switch (value)
{
case School.DVB: this.MySchool = "D";
break;
case School.AVD: this.MySchool = "A";
break;
case School.ASB: this.MySchool = "B";
break;
default: this.MySchool = null;
break;
}
}
}
旁注:使用 EF Core 有一种更优雅的方式来执行此类操作,而无需添加新属性。使用 EF Core 2.1,我们可以摆脱这个属性并使用Value Conversion。
最后,所有需要处理MySchool
数据库列的视图模型不应该使用MySchool
属性,而是将其对应的属性映射到MyShcoolEnum
您的实体的属性。
您的实体代码应与此类似:
public class MyEntity
{
public string MySchool { get; set; }
[NotMapped] // <-- This tell EF that this property is not mapped to the database.
public School? MyShcoolEnum
{
get
{
// Getting the value of this property depends on the value of the database
// which is stored into MySchool property.
switch (MySchool)
{
case "D": return School.DVB;
case "A": return School.AVD;
case "B": return School.ASB;
default: return null;
}
}
set
{
// When setting this property you automatically update the value of MySchool property
switch (value)
{
case School.DVB: this.MySchool = "D";
break;
case School.AVD: this.MySchool = "A";
break;
case School.ASB: this.MySchool = "B";
break;
default: this.MySchool = null;
break;
}
}
}
}
推荐阅读
- c# - 使用 Windows 身份验证的 IIS 匿名身份验证 - 未发出第二个请求
- apache-kafka - 卡夫卡制作人WARN
- html - 是什么导致此网页上图像右侧的空白区域?
- c++ - 在没有 Xcode 的 Mac Bundle 中嵌入框架
- c# - VS2015 C# WPF:如何添加事件处理程序?
- flutter - Flutter Stateful Widget 状态中断
- mongodb - 架构最佳实践 MongoDb
- android - SwipeRefreshLayout 阻止嵌套 RecyclerView 中项目的 onClickCallback
- android - TypedValue.applyDimension 产生错误的尺寸
- python - Syft (PySyft):ModuleNotFoundError 'syft_proto.messaging.v1.protocol_pb2'