有没有办法将字符串列映射到实体模型中的枚举?
我已在 Hibernate 中完成此操作,但无法在 EMF 中解决。
最佳答案
可能是更好的版本。
OrderStateIdentifier 字段用于 JSON 序列化和数据库字段, 而 OrderState 只是为了方便在代码中使用。
public string OrderStateIdentifier
{
get { return OrderState.ToString(); }
set { OrderState = value.ToEnum<OrderState>(); }
}
[NotMapped]
[JsonIgnore]
public OrderState OrderState { get; set; }
public static class EnumHelper
{
/// <summary>
/// Converts string to enum value (opposite to Enum.ToString()).
/// </summary>
/// <typeparam name="T">Type of the enum to convert the string into.</typeparam>
/// <param name="s">string to convert to enum value.</param>
public static T ToEnum<T>(this string s) where T: struct
{
T newValue;
return Enum.TryParse(s, out newValue) ? newValue : default(T);
}
}
关于c# - 将 Entity Framework 中的字符串列映射到枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7437952/