Justin Adkins
Justin Adkins

Reputation: 1234

Best way to store multiple enums in database

I have an Enum called RoleEnum with four values User (1), Supervisor (2), Admin (3), and ITOperator (4). I have an Announcement table that obviously stores Announcement data (title, text, start and end date). However, I'd like to be able to add a new column called Roles that defines which users in which roles can see the announcement.

Normally when storing Enums in SQL I just use the smallint data type, however that isn't going to work in this situation because an announcement can be seen by more than one role.

What I was considering doing was having the Roles column defined as a varchar(x) and comma delimiting them when they were stored. However, I don't think/know if that is the best route to take. I don't want to create a new table to hold a one-to-many relationship.

Any ideas?

Upvotes: 10

Views: 6908

Answers (3)

xxbbcc
xxbbcc

Reputation: 17327

This is one possible solution - not guaranteed to be the best but it doesn't require a new table.

You can add the [Flags] attribute on your enum - this makes the enum a bit field where individual enum values can be masked together. Your enum would then look like this:

[Flags]
public enum RoleEnum : long
{
    User = 1,
    Supervisor = 2,
    Admin = 4,
    ITOperator = 8
}

You can use the '|' (bitwise OR) operator to mask multiple roles together in a single 64-bit integer, which you can store in the database in an integer field (a bigint).

RoleEnum userRoles = RoleEnum.User | RoleEnum.Admin;

If you don't need 64 possible roles, you can drop down to using an int instead - that gives you 32 possible distinct roles.

Upvotes: 5

JDB
JDB

Reputation: 25810

If you care about maintainability, I'd stick with third normal form as much as possible.

Roles

RoleID  RoleName
1       User
2       Supervisor
3       Admin
4       ITOperator

Announcements

AnnouncementID  Title   ...
1               Foo     ...
2               Bar     ...

AnnouncementsVisibility

AnnouncementID  RoleID
1               1
1               2
2               2
2               3
2               4

Upvotes: 7

Chris Noffke
Chris Noffke

Reputation: 317

Just do as Entity Framework would do and store them as ints.

Check this out to learn more... MSDN

Upvotes: 0

Related Questions