Click here to Skip to main content
Click here to Skip to main content

Managing Enums and their Database Equivalents

By , 10 Nov 2008
 

Introduction

I like enumerations. They keep me safe, reduce error, and make the code more readable. However, since I do a lot of database work, they also cause synchronization issues. That is, my enums often have to match my database since I use them to represent values in data objects. It is also not uncommon to want to populate a list with values from an enum. I formerly used the database values to populate the list, but now I use the enum as my master and populate my lists from it.

The class I supply in this article solves some common problems:

  1. It synchronizes an enum with the database.
  2. It allows me to populate a list directly from the enum.

Using the Code

EnumManager provides three static methods:

  • UpdateEnum()
  • GetListFromEnum()
  • SeparatedValue()

UpdateEnum()

UpdateEnum() iterates through the values of an enum, and updates a database with the changed values. This means that the values named in the code match the names of the values derived from reports generated from the database. UpdateEnum() does not remove values, since that would generate an error when foreign keys were involved. Of course, care must be taken not to change the values arbitrarily since it could lead to incorrect data, but it does guarantee that what the code says is what the database says.

I usually run the update at initialization time, such as in Application_Start for ASP.NET. If you have a lot of enums to update, it would be best to do it in a separate thread to allow the application to start more quickly.

The parameters are pretty obvious:

UpdateEnum(Type type, string connectionString, string table, 
    string idColumn, string nameColumn)
  • type is the enum created by typeof(MyEnum)
  • connectionString should be obvious
  • table is the string name of the table to be updated. It must exist already.
  • idColumn is the value column for the numeric part of the enum
  • nameColumn is the name of the column that contains the string part

Of course, other columns may exist in the table, but there must be a numeric column and a string column that represent the enum values.

GetListFromEnum()

In order to bind a list such as a listbox or dropdown, we need a data source. List<> makes a great choice. Using generics, I return a KeyValue<> pair for each enum value. This makes binding to Key and Value very easy. For a listbox, it might look like this:

ListBox1.DataSource = GetListFromEnum<MyEnum>();
ListBox1.DataTextField = “Value”;
ListBox1.DataValueField = “Key”;
ListBox1.DataBind();

EnumManager works one other bit of magic in providing the values for the list. It splits words out of the enum value at capital letters. Thus, “ValueOne” becomes “Value One” when bound this way. Enums don't allow spaces in names, but lists for human consumption should be separated. SeparatedValue() accomplishes this little trick.

SeparatedValue()

Of course, SeparatedValue() can be used independently of lists and GetListFromEnum(). It simply takes an Enum (the value of on enum) and splits its name.

History

  • 10th November, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

LaurenCL
Web Developer
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionHow to bind with description?memberasp_crazy_guy12 Sep '12 - 20:16 
How to bind an enum with a description tag & a value?
 
<pre lang="c#">public enum Bubble
{
     [Description("Small Bubble")]
     sbubble=0,
     [Description("Large Bubble")]
     lbubble=1
}
 
Now I want to bind dropdownlist with
      Text='Small Bubble', value=0
      Text='Large Bubble', value=1  

GeneralMy WaymemberDmitri Nesteruk11 Nov '08 - 9:35 
Since I go the 'code generation' route, I do the following: define enums as XML, keep the SQL field as 'int', and generate options as a ObservableCollection in the DAL.
GeneralMy waymemberPIEBALDconsult11 Nov '08 - 4:19 
Yeah, enumerations are great.
 
My feeling is that the enum should match the table, not the other way around;
imagine removing a member from the enum and causing a referential integrity problem in the database.
 
As I've still not come up with a way to have a build query a table and generate a file containing an enum,
I've started reading that sort of table into Dictionaries and using them as pseudo-enums in my code.
(They just don't work with switches. Frown | :( )
 
Maybe I'll give it some more thought today...
GeneralRe: My waymemberLaurenCL11 Nov '08 - 6:13 
I view this kind of enums as intrinsicly part of the data just as much as the database. If one changes the enum willy-nilly, of course problems will occur. It would be essential that an enumeration used this way be controlled by a knowledgeable developer, and not "just anybody".
 
Do notice that I said in the article that I do not delete any database records since, as you say, it would lead to referential integrity issues.
GeneralHmmm...memberPaul Conrad10 Nov '08 - 18:08 
You may want to try adding more content to your article. Sounded interesting, but not much there.
 
"The clue train passed his station without stopping." - John Simmons / outlaw programmer
 
"Real programmers just throw a bunch of 1s and 0s at the computer to see what sticks" - Pete O'Hanlon
 
"Not only do you continue to babble nonsense, you can't even correctly remember the nonsense you babbled just minutes ago." - Rob Graham


GeneralRe: Hmmm...memberNeil de Weerdt10 Nov '08 - 20:20 
I have to agree with Paul..
Sounded great.
I was hoping for a design time enum that get’s build up from the DB.
But on the other hand it’s a good idea. Just watch out for mapping the values.
Don’t map text map the hashcode. So I would suggest storing the hashcode of the enum value
GeneralRe: Hmmm...memberLaurenCL11 Nov '08 - 6:15 
It's really very simple. I could write a lot more, but by the time you read it you can read the whle of the code for the class.
GeneralRe: Hmmm...memberPIEBALDconsult11 Nov '08 - 7:49 
Yes, but I, for one, don't download and read the code unless the article is complete and well-written and has snippets that indicate that the rest of the code is readable.
 
Even then I may only take the ideas presented and write my own.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 10 Nov 2008
Article Copyright 2008 by LaurenCL
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid