IT:AD:Patterns:Enums Mapped to Code Tables Strategy
Summary
Relational data (ie lookup tables) can be that categorised as either:
- immutable: static/unchanging throughout the foreseable future, and
- mutable: addable by the end user, support, etc.
Generally the immutable kind is used within the application's logic, and the mutable kind is hard to create logic around, as you don't know if the element you are referencing is going to be in the set in the future.
Tip: The two types should maybe get their own distinct table prefixes to distinguish between the two. * ref_ * ref_code_
The fact that the immutable code is used within the application's logic is interesting.
How does one intuitively work with it in code?
Process
Imagine the following scenario.
public class Person { public int Id {get;set;} public string Name {get;set;} public GenderFK {get;set;} public Gender Gender {get;set;} } public class Gender { public int Id {get;set;} public string Name {get;set;} }
The above is sound – Db wise – but a pain to work with in code:
Person person = _personRepository.Get(3); if (person.GenderFK == 2) {...hum...doable, but pretty opaque.}
We could use an enum:
public enum GenderType {Undefined=0,Unknown=1,Male=2,Female=3}; if (person.GenderFK == ((int)GenderType.Male)) {...hum...slightly better, but still not hugely impressed.}
With EF5, one can now use Enums: IT:AD:EF/CodeFirst:HowTo:Work with Enums
public class Person { public int Id {get;set;} public string Name {get;set;} [Ignore] //ie, don't persist it from the Db... public GenderType GenderType {get {return ((GenderType)GenderFK);} set {GenderFK = (int)value;}} public GenderFK GenderFK {get;set;} public Gender Gender {get;set;} }
I'm not sure if one can actually skip the int/Enum mapping ( I don't have an Visual studio to try it out tonight), but the above is sound, and will make it easy to keep a lookup table in the db, while keeping an enum in the code logic:
if (person.GenderType == GenderType.Male)) {...Fine by me.}
And if an enum can be used in the place of GenderFK, it would not even be needed. Would be nice.