解决应用程序层中的用户角色的好主意吗?
我需要基于角色的系统的原因:
- 限制对页面的访问。
- 限制对页面上某些功能的访问。
- 服务层内的检查/验证。
所以我猜测,我可以创建一个枚举,如果我需要一个新角色,只需将其添加到应用程序代码中(应用程序无论如何都会更改,因此需要重新编译)。
所以现在我有
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 multiple。我认为这样做的优点是,不是多对多,而是一对多,并且连接更少。应用程序已经根据 int
将枚举解析为的内容知道角色是什么。
我这样做的方式有什么缺陷吗?根据您的经验,是否遇到过需要我将实际值存储在数据库中的情况?
The reason I need a role-based system:
- Restrict access to pages.
- Restrict access to certain features on pages.
- 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 values in the database?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
需要明确的是,您建议您不需要在数据库中为角色提供实际的查找表?相反,它们只是有一个 int,它不是任何东西的外键——它只是应用程序中枚举的表示?
如果不了解您申请的所有详细信息,就不可能给出明确的答案。除了免责声明之外,我认为它本身没有什么问题。对于某些系统来说它肯定可以正常工作。
可能的缺点:
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: