FluentNHibernate and Enums

后端 未结 2 541
梦谈多话
梦谈多话 2021-02-11 01:01

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

2条回答
  •  醉梦人生
    2021-02-11 01:54

    So, after a few days of talking to other developers, digging around online, and posting to the FluentNHibernate group on google, I have discovered that collections of enums are currently not exactly supported. If there is a way to do what I want to do, well, it's undocumented or a workaround.

    So, I went back to the drawing board with what I was doing and really thought about it. Basically, my only choice was to use a class for my permissions. But, I want to use my enum in code, and that's when it hit me. The PermissionId field can be converted from an int to the enum and vice versa. Also, using some logic I have done before when using an enum of roles with the built in ASP.NET provider, I can write an administrative tool that will build permissions based on what is in my enum.

    First, I renamed my enum.

    public enum PermissionCode
        {
            //site permissions 1-99
            [StringValue("View Users")]
            ViewUser = 1,
    
            [StringValue("Add User")]
            AddUser = 2,
    
            [StringValue("Edit User")]
            EditUser = 3,
    
            [StringValue("Delete User")]
            DeleteUser = 4,
        }
    

    Then, I created a new Permission class. This class mirrors the database and is simply an int Id and a string name. However, I added one property to convert that id into my PermissionCode enum.

    public class Permission
        {
            public virtual int PermissionId { get; set; }
            public virtual string PermissionName { get; set; }
    
            public virtual PermissionCode PermissionCode 
            {
                get
                {
                    return (PermissionCode)PermissionId;
                }
            }
        }
    

    Then, in my User and Role objects, I reference Permission, and I can still do matchups like bool UserHasPermission(PermissionCode.DeleteUser);

    Then in global.asax, on Application_Start I will check the webconfig for a flag that will indicate if the permissions need to be rebuilt. This way I can enable the rebuild only when I need to without having to have a permission to get in and possibly needing to deal with an error. This means I only maintain a single list of permissions in my enum, which is ideal.

    Granted, the overall approach isn't as slick as I wanted, but it works. Does anyone have any other suggestions?

提交回复
热议问题