I have an enum called Permissions. A user can be assigned permissions, or permissions can be asigned to a role and the user can be given a role.
User and Role both have a property like this:
public virtual IList<Permission> Permissions { get; set; }
I want to use an enum for Permissions so in my code I can do things like
public static bool UserHasPermission(Permission.DeleteUser)
Right now I have about 50 different permissions in my enum. It would be nice if I didn't have to populate a mirror set of data in the database. My enum looks like this:
public enum Permission
{
//site permissions 1-99
[StringValue("View Users")]
ViewUser = 1,
[StringValue("Add User")]
AddUser = 2,
[StringValue("Edit User")]
EditUser = 3,
[StringValue("Delete User")]
DeleteUser = 4
...
}
Currently, I have a table for Permissions that is the PermissionId (int) and PermissionName (varchar (50)).
Here are my tables on the roles side. The user side is exactly the same as far as permissions go:
CREATE TABLE dbo.Roles
(
RoleId int IDENTITY(2,1) NOT NULL,
RoleName varchar (50) NOT NULL,
CONSTRAINT PK_Roles PRIMARY KEY CLUSTERED (RoleId)
)
CREATE TABLE dbo.RolePermissions
(
RolePermissionId int IDENTITY(1,1) NOT NULL,
RoleId int NOT NULL,
PermissionId int NOT NULL,
CONSTRAINT PK_RolePermissions PRIMARY KEY CLUSTERED (RolePermissionId),
CONSTRAINT FK_RolePermissions_Roles FOREIGN KEY (RoleId) REFERENCES Roles(RoleId),
CONSTRAINT U_RolePermissions UNIQUE(RoleId, PermissionId)
)
Then, I have a permissions tble in case I need it, but I just don't get how to map either the id field in RolePermissions or the Permissions table back to the enum.
CREATE TABLE dbo.Permissions
(
PermissionId int NOT NULL,
PermissionName varchar (50) NOT NULL,
CONSTRAINT PK_Permissions PRIMARY KEY CLUSTERED (PermissionId)
)
- Can I map the enum to the table?
- Should I even map it, or should I just take out the Permissions table and in UserPermissions and RolePermissions leave PermissionId just an int and map the into to the enum?
- If I keep the Permissions table, is there a way for nhibernate to autopopulate the data in the Permissions table from the data in the enum?
Right now, I have no mapping to the permission enum, other than something like this:
HasManyToMany(x => x.Permissions)
.WithParentKeyColumn("RoleId")
.WithChildKeyColumn("PermissionId")
.WithTableName("RolePermissions")
.LazyLoad()
.Cascade.All();
Unfortunately, this causes an error:
An association from the table RolePermissions refers to an unmapped class: GotRoleplay.Core.Domain.Model.Permission
What am I doing wrong with enums? Is there a standard way or best practice for using them with fluentnhibernate when the enum is a list of values on the object and not just a single value?