1

I created a new Enum class from db table Role which has RoleId and RoleType.

public enum UserType
{
    Student = 1,
    Teacher = 4
    Admin = 5 
}

Here 1,4,5 are RoleId(Primary Key) from db. What i did is i looked manually for the db primary key value for each role and mapped that to enum.

The demerit here is every time i need to update the enum class when db RoleId Changes.

Is there any other standard practice to map db values as enum collections?

Any suggestions will help

Hary
  • 5,690
  • 7
  • 42
  • 79
  • Just cast the value. `(UserType)some_value;` – Darren Kopp Feb 25 '13 at 05:05
  • what do you meant? `(UserType)some_value`. I am asking for mapping db values to `enum`. How does it helps? – Hary Feb 25 '13 at 05:06
  • http://stackoverflow.com/questions/725043/dynamic-enum-in-c-sharp – 4b0 Feb 25 '13 at 05:07
  • If you're using EF and code-first, you should be able to just use the Enum: http://msdn.microsoft.com/en-us/data/hh859576.aspx See also: http://stackoverflow.com/questions/6344032/enums-with-ef-code-first-standard-method-to-seeding-db-and-then-using – lc. Feb 25 '13 at 05:08

1 Answers1

3

Recently, I've been facing same problem. One of the possible solutions is using T4 template (codegeneration). You can implement some custom logic to select table(s) and description/value columns. Something like this

    //Start write enum file:        
    #>
    namespace <#=enumNameSpace#>
    {
        public enum <#=enumName#>Enum
        {
        <#
          command.CommandText = string.Format("SELECT * FROM {0}",TABLE_NAME_GOES_HERE);
          var columnReader = command.ExecuteReader();
          while (columnReader.Read())
          {#>   
               <#=columnReader[DESCRIPTION_COLUMN_NAME].ToString()#> = <#=columnReader[VALUE_COLUMN_NAME].ToString()#>,
          <#    
          }#>
        }
    }
    <#

You can read more in this great article

Konstantin Chernov
  • 1,899
  • 2
  • 21
  • 37