I use an EnumHelper
method and try to get both description and enum
value (Id) as shown below:
EnumHelper:
public static class MyEnumHelper
{
public static string GetDescription<T>(this T enumerationValue)
where T : struct
{
System.Type type = enumerationValue.GetType();
if (!type.IsEnum)
{
throw new ArgumentException("Must be Enum type", "enumerationValue");
}
//for the enum
MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
if (memberInfo != null && memberInfo.Length > 0)
{
object[] attrs = memberInfo[0]
.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
{
return ((DescriptionAttribute)attrs[0]).Description;
}
}
return enumerationValue.ToString();
}
}
Enum:
public enum StatusEnum
{
[Description("Deleted")]
Deleted= 0,
[Description("Active")]
Active= 1,
[Description("Passive")]
Passive= 2
}
Entity:
public class DemoEntity
{
public int Id { get; set; }
public StatusEnum StatusId { get; set; }
[NotMapped]
public string StatusName
{
get { return MyEnumHelper.GetDescription(StatusId); }
}
}
Controller:
DemoEntity entity = DemoEntity();
entity.StatusId = StatusEnum.Passive;
// !!! This returns "Passive" instead of its value 2. How can I get its value?
However, when trying to assign Id
value of an enum
by using strongly type feature of the enum
as shown above, I still get its description instead of Id
. Any idea about where the problem is?
just cast your enum to int if you need the value
entity.Id = (int)StatusEnum.Passive;
I would have perhaps done this:
public enum Status
{
Deleted= 0,
Active= 1,
Passive= 2
}
public class DemoEntity
{
public int Id { get; set; }
public Status Status { get; set; }
[NotMapped]
public string StatusName
{
get { return this.Status.ToString("g"); }
}
[NotMapped]
public int StatusId
{
get { return (int)this.Status; }
}
}
((Status)3).ToString()
returns "3");Consider the library Enums.Net if you're getting heavy into work with enums
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.