Bitwise operations on enums based on attributes

Viewed 75

I have quite big enum with custom numbers like

 public enum DataSources
    {
        Undefined = 0,
        [Description(nameof(Resources.Web))]
        Web = 1,
        [Description(nameof(Resources.Mail))]
        Email = 2, 
        [Parent(Value = (int)Other)]
        [Description(nameof(Resources.VoIP))]
        Voip = 5,
        [Parent(Value = (int)Other)]
        [Description(nameof(Resources.ProcessAndApplications))]
        Processes = 257,
        ...

And now I'm looking a way to store multiple DataSources (enum above) values in another class let's call it Role (it's db entity represents row in database).

class Role : DbEntity
{
        [PrimaryKey, Identity]
        public override long Id { get; set; }
        [Column(Name = "name"), NotNull]
        public string Name { get; set; }
        public DataSources dataSources {get;set;}
} 

Usually I could use [Flags] but I can't change already assigned values for DataSources enum. Is there any solution in this case? May be I could use additional attributes for bit values?

1 Answers

You could store multiple values in a single column by using bitwise OR. But this requires that all enum values occupy unique bits. I can already see this is not going to be possible in your case because you have more than one odd number.

The next option is to extract the DataSources column into its own table and add a FK to it from Role. Your Role class changes as shown below.

class Role : DbEntity
{
    [PrimaryKey, Identity]
    public override long Id { get; set; }
    [Column(Name = "name"), NotNull]
    public string Name { get; set; }
    public IList<RoleDataSources> DataSources {get;set;}
}

class RoleDataSources : DbEntity
{
    [PrimaryKey, Identity]
    public override long Id { get; set; }
    [ForeignKey("Role"), Identity]
    public long RoleId { get; set; }
    public Role Role { get; set; }
    public DataSources Value { get; set; }
}
Related