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

后端 未结 3 1761
独厮守ぢ
独厮守ぢ 2020-12-31 16:35

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 |         


        
相关标签:
3条回答
  • 2020-12-31 17:04

    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 };
    context.Save();
    
    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.

    0 讨论(0)
  • 2020-12-31 17:06

    You can save a combination of flags as an int:

    int myFlags = (int)(Target.Group | Target.Professor);
    
    0 讨论(0)
  • 2020-12-31 17:06

    The only difference between enum types with and without HasFlagAttribute is how they are written when using .ToString() (and maybe how they are parsed when using Enum.Parse). EF internally strips the information about enum type and is only using the underlying enum type (accounting for nullability).

    0 讨论(0)
提交回复
热议问题