Saving enums as strings with Entity Framework

Full source code here.

I hit a problem where I wanted to use Entity Framework to save the text value of an enum to the database rather than its numeric value. This is not possible with Entity Framework at the moment; there are a few hacky solutions out there. I add my own hacky solution here.

I have a Person class with an ID, name and gender; the gender is an enum with just male and female. I’d like to save “Male” or “Female” to the database instead of 1 or 2.

The enum is simple.

    public enum Gender
    {
        Male = 1,
        Female = 2
    }

The Person class makes use of Data Annotations to perform the correct mappings to the table. The Gender property is not mapped to the database while the GenderString is mapped as the column named Gender.

    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<Gender>(); }
        }

        [NotMapped]
        public Gender Gender { get; set; }
    }

I use an extension method to parse the text value of gender back into the enum.

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

Rows in the table will now have the string value of the enum rather than that number.

PersonIDFirstNameLastNameGender
1JamesSmithMale
2JaneSmithFemale

And when a person is loaded from the database the Gender enum is correctly populated.

The only drawback is that there is now a public property called Gender and GenderString on the Person class, but I have made the set of GenderString private to prevent accidental updating.

Full source code here.