Can I store enums as strings in EF 5?

后端 未结 2 1845
面向向阳花
面向向阳花 2021-01-04 00:29

We have been using EF CF for a while in our solution. Big fans! Up to this point, we\'ve been using a hack to support enums (creating an extra field on the model; ignore the

2条回答
  •  醉话见心
    2021-01-04 01:00

    I hit this problem a few weeks ago. The best I could come up with is a bit hacky.

    I have a Gender enum on the class Person, and I use data annotations to map the string to the database and ignore the enum.

    public class Person
    {
        public int PersonID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    
        [Column("Gender")]
        public string GenderString
        {
            get { return Gender.ToString(); }
            private set { Gender = value.ParseEnum(); }
        }
    
        [NotMapped]
        public Gender Gender { get; set; }
    }
    

    And the extension method to get the correct enum from the string.

    public static class StringExtensions
    {
        public static T ParseEnum(this string value)
        {
            return (T)Enum.Parse(typeof(T), value, true);
        }
    }
    

    See this post for full details - http://nodogmablog.bryanhogan.net/2014/11/saving-enums-as-strings-with-entity-framework/

提交回复
热议问题