Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save Flag Enums in SQL Database and EF6. Is this possible?

On an ASP.NET application I have a flag enum as follows:

[Flags]
enum Target : int {
  None = 0,
  Group = 1,
  Student = 2,
  Professor = 4,
  All = Group | Student | Professor
}

Can I save a value containing more than one item in a SQL Database Table using Entity Framework 6?

How would that be saved?

Thank You, Miguel

like image 917
Miguel Moura Avatar asked Jan 09 '14 13:01

Miguel Moura


People also ask

How do I store multiple enums in a database?

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.

What is flagged enum?

A flagged enum can be used to efficiently send and store a collection of boolean values. In a flagged enum, each value of the enum is assigned to a bit value. These must be bit values because each combination possible will be unique.

How to Add enum in Entity Framework?

Use an Existing Enum from a Different Namespace If you already have an Enum type created in your code, then you can use that as a data type of any entity property. To use an existing Enum type, right click on Designer → Add New → Enum Type. Enter the Enum Type Name in the dialog box.


1 Answers

You can save a combination of flags as an int:

int myFlags = (int)(Target.Group | Target.Professor);
like image 51
Alberto Avatar answered Oct 17 '22 05:10

Alberto