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.
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.
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
I use an extension method to parse the text value of gender back into the enum.
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
GenderString on the
Person class, but I have made the set of
GenderString private to prevent accidental updating.