Follow up to writing enums to a database

In my previous blog entry, I had recommended storing enums using their string representations when writing them to a database. There’s a caveat there though – the enum names should be guaranteed to remain stable, because if you change the name of an enum member, it breaks the database. For my specific scenario I ended up using enum values with explicit short values, so if the names ever change in future the short values remain the same and thus the database remains consistent.

There are other approaches to solving this too. Reader Arnaud Weil suggests having a table for each enum and the enum id from this table is used to refer to the enums elsewhere in the database. The guys at my current project have a specialized class that emulates enums and also allows the ability to associate meta-information to each enum value (like an image or a description). A third approach would be to use custom attributes and a type descriptor that’d extract the meta-information from an enum type. The old adage is true – there are many ways to skin a cat.

Recommendation for writing enums to a database

I was reviewing some code and found that there were a few enum types that did not have a None value (which is a recommended practice). I thought I’d go ahead and add the None values when I found that the enum values were being written to the database via calls to Convert.ToInt32. Of course this meant that I could not add a None member as the first value since it’d break the database. If all of the enum members specified explicit int values I probably could still add a None member, but even that is kinda messy.

My recommendation is to store enums as strings in the database. Now you can change the order of the members, add and remove members etc. with absolutely no issues. Converting between an enum value and its string name is rather trivial too.