简体   繁体   中英

Binding enums to static data

I'm working on an application that has to manage permissions, and I've come up with a design I wanted some feedback on. I'm not sure if this is exactly the right place to post it but I guess we'll see.

A user in my application can be assigned permissions. They can have permissions on an individual level, or from being part of a group. Thus I have the following tables (I think the names are relatively self-explanatory but can add further information if needed):

  • Users
  • Permissions
  • User_Permissions
  • Groups
  • User_Groups
  • User_Group_Permissions

The design of the permissions table is this:

  • id int (permission id, primary key)
  • name varchar(255) (name of the permission, such as "ADMINISTRATION")
  • description varchar(1000) (A short description of the permission)
  • default_value tinyint (The default value to assign to users (Yes/No/Never))

However, when I check the permission in code, I didn't want to use a "Magic String" so I created an enum for the permissions in my permissions table, and then use it like so:

public enum EPermission
{
    ADMINISTRATION = 1,
    LOGIN = 2
}

public bool HasPermission(EPermission permission)
{
    int permission_id = (int)permission;
    //look up the permission in the database based on permission_id
}

The ids in my permissions table match the number values I've assigned in my enums. The application has no way of changing these. The permissions in the permissions table are inserted with those ids as part of the installation and should not be changed.

Is this kind of coupling acceptable? I'm not expecting the data to change, but it's always possible that it could, and I'm just wondering if there might be a better way to do things before I get too deep into this.

Yes it is "acceptable" and a fairly common practice.

EDIT: If you wanted to really minimize the chance that your DB and the enum will become out of sync, you can reflect the enum to seed your table with data during deployment.

As you do not change the Permissions you can also get away from the permissions table and only use the enum. You can then store the value of the enum as an int in the User_Permissions and User_Group_Permissions tables.

When retrieving the data from the database you can deserialize the value to the enum. This reduces the possibility that the data in your database gets corrupted and does not match with your enum anymore.

I suspect that it will not help long run. what If a single user can have one or more permissions. Then you need to switch flag enum?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM