Save flags in SQL and EF6 database. Is it possible?

In an ASP.NET application, I have a flag enumeration as follows:

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

Is it possible to save a value containing more than one item in a SQL database table using Entity Framework 6?

How will it be saved?

Thanks Miguel

+4
source share
3 answers

To make things really simple, flags can be thought of as an int sum (just being simple, but they actually work with bitwise operations).

So, for your case (subject to listing), if there are two goals in the record (student and professor), the final result will be 6.

EF . 6. , EF INT, , int :

enum Target : int {

( !) .

, , Enum.Parse, ( ), EF .

. , , :

var item = new Something() { Prop = Target.Student | Target.Professor };
context.Save();

var item2 = context.GetSomething();

if (item2.Prop.HasFlag(Target.Professor) && item2.Prop.HasFlag(Target.Student))
{
   // WOW!
}

. EF6, . , CodeFirst.

, .NET framework. Enum EF.

+13

int:

int myFlags = (int)(Target.Group | Target.Professor);
+1

The only difference between enumeration types with and without HasFlagAttributeis how they are written when used .ToString()(and, possibly, how they are analyzed when using Enum.Parse). EF internally separates enumeration type information and uses only the base enumeration type (null-sensitive).

0
source

All Articles