SQL Table and C# Enumeration

前端 未结 4 1475
北恋
北恋 2020-12-28 17:33

Suppose I have n types of users in my application.

I am using an UserType enumeration to distinguish them.

Do I need to keep a table in

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-28 18:34

    You can set this as an int column in the database, and then use the Flags() attribute for your enumeration. You're limited to 32 UserTypes (2^32) however.

    [Flags]
    public enum UserType
    {
        None = 0,
        Viewer = 1,
        ContentEditor = 2,
        Editor = 4,
        Admin = 8,
        Root = 16,
        Disciple = 32,
        God = 64
    }
    

    Update
    I skipped the part about not wanting to read through the source. How is the source using the enumeration? If it's using the number then the look-up table won't affect performance and is a good idea for reference. If the application is using a string name, then maybe it would be easier to adopt the ASP.NET roles provider (iirc) technique of simply using an indexed varchar column for UserType, on the user table.

    So:

    Name    Email           UserType
    Bob     blah@blah.com   admin,author
    

    There can still have a reference table if needed.

    I stick to the enumeration solution in the code, but that's because on most of the projects I'm involved with the roles list is static. So if the roles do need to be customisable then a separate look-up table would be the best option, but still using the flags system mentioned above (instead of an intermediate many-to-many table).

    Also for a large amount of users, the de-normalized Flags system would be preferable and I'd guess faster. Do you care enough about 3rd normal form for the many-to-many way (but one that ensures better referential integrity). The comma separated list of roles would probably be just as fast and less cumbersome to manage for a small set of users.

提交回复
热议问题