Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return values from Entity Framework with parameters based on a bitwise Enum

Bit (sorry) confused about how to use bitwise operators with Entity Framework.

A recent requirement has necessetated that we alter an enum from a series of sequential integers into a bitwise enum. So:

[Flags]
public enum AdminLevel
{
    None = 0,
    Basic = 1,
    Partial = 2,
    Full = 4
} 

We originally stored this as an int column in the database. It's still an int, of course, but I'm having trouble seeing how I can perform selections based on more than one possible enum value. For example this code:

public string GetAdminEmails(AdminLevel adminlevel)
{
    using (IRepository r = Rep.Renew())
    {
        string[] to = r.GetUsers().Where(u => u.AdminLevel >= (int)adminlevel).Select(u => u.Email).ToArray();
        return string.Join(",", to);
    }
}

Would return all the admin levels including and above the one supplied. If I want more than one admin level, I now have to call it like this:

GetAdminEmails(AdminLevel.Partial | AdminLevel.Full);

But obviously I can't convert that to an int and use greater than any more. Is there a neater way of handling this change than a series of flow control statements?

like image 953
Bob Tway Avatar asked Jul 19 '26 23:07

Bob Tway


1 Answers

You can use the HasFlag method:

AdminLevel myFlags = AdminLevel.Partial | AdminLevel.Full;
string s = GetAdminEmails(myFlags);

public string GetAdminEmails(AdminLevel myFlags)
{
  using (IRepository r = Rep.Renew())
  {
      string[] to = r.GetUsers().Where(u => u.AdminLevel.HasFlag(myFlags))
                                .Select(u => u.Email).ToArray();
      return string.Join(",", to);
  }
}

You can define an int column in your database as an enumeration in your model:

public enum MyEnum : int { First = 0, Second = 1}

public partial class MyModel
{
   public MyEnum Type {get; set;}
}

Throughout your application you can just use MyEnum and EF will work with int on the background.

like image 76
Alexander Derck Avatar answered Jul 21 '26 13:07

Alexander Derck