0

For example:

public class Role
{
    public Role()
    {
        Permissions = new HashSet<Permission>();
    }

    public string ID { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Permission> Permissions { get; set; }
}

public enum Permission
{
    UserManagement = 0,
    DepartmentManagement = 1,
    RoleManagement = 2,
    ModifyPassword = 3
}

Normally, between a model and another model, I can write two navigation properties. But for this situation, I cannot write a navigation property in an enum.

Plantain Yao
  • 401
  • 5
  • 10

1 Answers1

4

Could you do something like this instead?

[Flags]
public enum Permission
{
    UserManagement = 1,
    DepartmentManagement = 2,
    RoleManagement = 4,
    ModifyPassword = 8
}

public class Role
{
    public string ID { get; set; }
    public string Name { get; set; }
    public Permission Permissions { get; set; }
}

And then, for example:

var role = new Role();
//assign multiple values
role.Permissions = Permission.UserManagement | Permission.ModifyPassword;
//add a value
role.Permissions |= Permission.DepartmentManagement;
//remove a value
role.Permissions &= ~Permission.DepartmentManagement;
//test for a value
bool hasPermission = (role.Permissions & Permission.ModifyPassword) != 0;

Warning:

Possibly consider exposing a few methods like RemovePermission(...), AddPermission(...), etc to make it harder to introduce a pretty significant bug if someone mishandles a bitwise operations.

Unless it's a performance requirement or something, I'd probably just make permissions a class and live with the overhead.

Some reading:

Community
  • 1
  • 1
Kyle
  • 1,366
  • 2
  • 16
  • 28