tags:

views:

459

answers:

6

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?

+1  A: 

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.

Ruben
That's what I do as well, but you still have problems if the integer stored in the code or the database is changed without updating the other.
Stewart Johnson
+1  A: 

Or maybe store the enumvalues as string in the DB. ToString();

Wolf5
A: 

We use a small application that generates enum code (example: NorthwindEnums.cs) from the database. We make sure to run it and update affected libraries whenever the database changes.

We also try to keep our enums starting at 0 and sequential to avoid issues with web service references in C#.

Todd Smith
+1  A: 

Using enum values is acceptable to do as long as you never change the already assigned values. If you were using the standard role-based authorization in .NET you would still be relying on the exisistence of certain text strings in the corresponding role table in the database.

Jonas Kongslund
A: 

A while back I built a little tool to do this for my company that would use attributes on the enum fields to allow "synchronisation" with the table in the database.

The tool could scan an assembly and generate appropriate INSERT/UPDATE SQL commands that would sync the database with the enum definition in the code.

Craig Shearer
A: 

I add an extended property on any table that I will need to access in code as an enum. I then use code generation software (codesmith, T4, whatever) to generate all my enum's for me by looking up any table with this property. Any table that is to be used for this abides by some basic rules (must have a Name column, etc.) so the code generator knows which column to use as the name for the enum's elements.

Once values are added to those tables we take care to virtually never change them to avoid breaking the build.

Mike