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.

Advertisements

3 thoughts on “Recommendation for writing enums to a database

  1. Thanks for the tip. This comes as a good design pattern for working with enums.

    My own design pattern for enums is to create a database table for each enum and then simply refer their IDs from the parent table. Obviously this is bulkier than your solution, but I’ve found that in a changing software enums often become objects (e.g. have several values related to each enum value), so when a table is there handling such changes is easy.

  2. Thanks for the feedback Arnaud. I agree with that. In fact I eventually decided to have enums with explicit short values that are inserted into the database. This way, if someone renames an enum member in future, it won’t break the database.

  3. Yes, I’m also tempted to use separate Tables for each Enum. Benefits are that the database forces you to only have correct values for the enum, because in .net one can set any value for an enum, but the database would then throw a fit (rightly). Also when looking at the database at any time, its easier to see whats going on and what a value means.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s