Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid dependencies between Enum values in code and corresponding values in a database?

Tags:

c#

enums

I have a number of user permissions that are tested throughout my ASP.NET application. These permission values are referenced in an Enum so that I can conveniently test permissions like so:

  • btnCreate.Enabled = PermissionManager.TestPermission(Permission.AllowCreate);

However, I also have these permissions stored in the database because I need hold more info about them than just their Id. But this creates a horrible dependency between the enum values and those in the database, an ill considered change to either and I have problems throughout my application. Is there a better way around this issue? Has anyone dealt with this before?

like image 419
flesh Avatar asked Nov 15 '08 10:11

flesh


1 Answers

I do not know what the best solution is, I would like to hear that. Our solution is to explicitly type the enum like

public enum MyEnum : int 
{
   None =0,
   Value = 1,
   AnotherValue =2 
}

And save the integer value to the database. When for instance the Value 1 is removed, you will still be able to use the enumeration and AnotherValue still has the value 2 in the database.

like image 88
Ruben Avatar answered Oct 16 '22 15:10

Ruben