Saving enums as strings with Entity Framework

In September 2018 I wrote a new post explaining how to store enums as ints or strings with Entity Framework Core. It is a nicer solution than the one presented here.

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.

1    public enum Gender
2    {
3        Male = 1,
4        Female = 2
5    }

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.

 1    public class Person 
 2    {
 3        public int PersonID { get; set; }
 4        public string FirstName { get; set; }
 5        public string LastName { get; set; }
 7        [Column("Gender")]
 8        public string GenderString
 9        {
10            get { return Gender.ToString(); }
11            private set { Gender = value.ParseEnum<Gender>(); }
12        }
14        [NotMapped]
15        public Gender Gender { get; set; }
16    }

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

1    public static class StringExtensions
2    {
3        public static T ParseEnum<T>(this string value)
4        {
5            return (T)Enum.Parse(typeof(T), value, true);
6        }
7    }

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


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.

comments powered by Disqus