Map string column in Entity Framework to Enum

前端 未结 8 1302
被撕碎了的回忆
被撕碎了的回忆 2021-02-18 13:46

Is there a way to map a string column to an enum in an Entity Model?

I have done this in Hibernate, but can\'t figure it out in EMF.

8条回答
  •  天命终不由人
    2021-02-18 14:23

    Probably a nicer version.

    OrderStateIdentifier field is used for both JSON serialization and database field, while OrderState is only used in the code for convenience.

        public string OrderStateIdentifier
        {
            get { return OrderState.ToString(); }
            set { OrderState = value.ToEnum(); }
        }
    
        [NotMapped]
        [JsonIgnore]
        public OrderState OrderState { get; set; }
    
    
    public static class EnumHelper
    {
        /// 
        /// Converts string to enum value (opposite to Enum.ToString()).
        /// 
        /// Type of the enum to convert the string into.
        /// string to convert to enum value.
        public static T ToEnum(this string s) where T: struct
        {
            T newValue;
            return Enum.TryParse(s, out newValue) ? newValue : default(T);
        }
    }
    

提交回复
热议问题