开发者

Good idea to resolve User roles in the application layer?

The reason I need a role-based system:

  1. Restrict access to pages.
  2. Restrict access to certain features on pages.
  3. Check/validation inside service layer.

So I'm guessing, I can just create an enum and if I need a new role, just add it to the app code (the app would change anyways so requires a recompile).

So right now I have

public class User
{
   /* .. */
   public virtual ICollection<UserRole> Roles {get; set;} 
}

public enum UserRoleType
{
    Administrator,
    User
}

public class UserRole
{
    public int UserRoleId { get; set; }

    public int RoleTypeValue { get; set; }

    public UserRoleType RoleType
    {
        get { return (UserRoleType)RoleTypeValue; }
        set { RoleTypeValue = (int)value; }
    }

    public virtual User User { get; set; }
}

This is a 1 to many. The pros I see for this is that instead of a many-many, there is a 1-many and joins are less. The application already knows what the role is based on what the int resolves the enum to.

Are there any flaws in the way Im doing this? Is there anything you have met in your experience that would require me to store the actual value开发者_如何学运维s in the database?


To be clear, you are suggesting that you don't need an actual lookup table in the database for Roles? Instead, they just have an int that is not a foreign key to anything--it is simply a representation of the enum in the application?

It's impossible to answer definitively without knowing all the details of your application. That disclaimer aside, I see nothing inherently problematic about it. It would certainly work fine for some systems.

Possible downsides:

  • There is no source of valid values enforced on the database side via referential integrity. What is to stop someone from entering "12452" for the RoleId in the database column? There are other ways around this like using check constraints, but they are not necessarily easier to maintain than a lookup table.
  • There is no way to effectively query the user/roles tables and have a human-readable representation of roles without knowing what the RoleIds represent (you will have to have the enum in front of you to make sense of the query result).
  • If the database is used for other applications, the roles will need to be represented (and maintained) in that application as well.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜