Map string column in Entity Framework to Enum

前端 未结 8 1307
被撕碎了的回忆
被撕碎了的回忆 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:31

    I had the same problem. I've come up with a solution, but I'm not completely happy with it.

    My Person class has a Gender enum, 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 = EnumExtensions.ParseEnum(value); }
        }
    
        [NotMapped]
        public Gender Gender { get; set; }
    }
    

    here is the extension method to get the correct enum from the string.

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

    I wrote a blog post about this - http://nodogmablog.bryanhogan.net/2014/11/saving-enums-as-strings-with-entity-framework/

提交回复
热议问题