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

c# entity-framework sql


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

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

1/9/2014 1:06:05 PM

Accepted Answer

To put things really simple, flags can be seen as an int sum (just to be simple but actually they work with bitwise operations).

So, for your case (provided enum), if a record has two targets (Student and Professor), the final result will be 6.

EF will store just this. 6. You have already told that EF should store this column as an INT because you've said that the enum should be understood as an int here:

enum Target : int {

There is no need to do anything (absolutely anything!) else.

To get this back into both Student and Professor, there is an Enum.Parse that you can call manually (only when needed) but EF will also populate the property with this already converted.

On your code, you'll have to worry just about the code. So, for instance, you can do:

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

var item2 = context.GetSomething();

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

That's just it. I'm using this with EF6 and there is no configuration at all. At least with CodeFirst approach.

But don't forget that this will work only with newer versions of .NET framework. Take a look into the Enum support topic from EF docs.

1/9/2014 3:48:56 PM

Popular Answer

You can save a combination of flags as an int:

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

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow