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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With