Enum flag and mutually exclusive Enum with overlapping value

I have a model that must be in one of the following mutually exclusive states: New , Running, or Closed .

The application allows the user to save the record and then retrieve them, providing a list of matching states.

I inherited an SQL database where the state is stored as an integer representing bitwise flags. I need to call a procedure that performs a mapping to a bitwise operation:

CREATE PROCEDURE SearchByState @MatchingStates int AS BEGIN SELECT Id, State FROM Records WHERE @MatchingStates & State > 0 END; GO 

This is all right.

Now, in a C # implementation, it’s pretty clear that I have to define flags to represent a combination of matching states in a request:

 [Flags] public enum States { None = 0x0, New= 0x1, InProgress = 0x2, Closed = 0x4, All = New | InProgress | Closed } 

The problem is that the record model must have a property representing one state.

The question is what should be the type of State property of the model of this record:

1) Just use the listing flags:

 public class Record { public int Id { get; set; } // Must ensure the value is equal to one of // States.New, States.InProgress, or States.Closed public States State { get; set; } } 

2) Define a new enumeration type for a mutually exclusive state:

 public enum State { New, InProgress, Closed } public class Record { public int Id { get; set; } // Must be stored as the value of one of // States.New, States.InProgress, or States.Closed public State State { get; set; } } 

Deficiency # 1 is semantic: enumeration of states is a combination of states, and not a single state.

Drawback # 2 is practical: when I save the state, I have to determine the base value that needs to be saved.

Can you imagine a way to represent all this while minimizing these shortcomings?

+4
source share
2 answers

I would leave it as a single, non-flag listing.

When you pass this to your procedure, you can build an integer from the enum using a bitwise or (|) or even just add values ​​(cast to int). I would try to avoid β€œbreaking” your logic in order to make one inherited request, and instead process the code that calls the request to handle unusual requirements there.

This ensures that code is clean everywhere. The "state" in your case should not be a flag enumeration - there is only one possible state.

+4
source

I would go with option # 2, and then modify your Get / Set statements to determine the base value each time. Thus, this is done for you every time you call properties. Code once, and you're done.

+1
source

All Articles