Differences

This shows you the differences between two versions of the page.

Link to this comparison view

it:ad:patterns:enums_mapped_to_code_tables_strategy [2019/03/24 12:02] (current)
Line 1: Line 1:
 +# IT:​AD:​Patterns:​Enums Mapped to Code Tables Strategy #
  
 +
 +
 +<callout type="​Navigation"​ class="​small">​
 +* [[../​|(UP)]]
 +{{indexmenu>​.#​2|nsort tsort}}
 +
 +
 +</​callout>​
 +
 +
 +<panel title="​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?
 +
 +
 +</​panel>​
 +
 +
 +## Process ##
 +
 +Imagine the following scenario.
 +
 +<sxh csharp>
 +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;}
 +}
 +</​sxh>​
 +
 +The above is sound -- Db wise -- but a pain to work with in code:
 +
 +<sxh csharp>
 +
 + ​Person person = _personRepository.Get(3);​
 + if (person.GenderFK == 2)  {...hum...doable,​ but pretty opaque.}
 +</​sxh>​
 +
 +We could use an enum:
 +
 +<sxh csharp>
 +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.}
 +</​sxh>​
 +
 +
 +With EF5, one can now use Enums: [[IT/​AD/​Code First/​HowTo/​Work with Enums]]
 +
 +
 +<sxh csharp>
 +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;}
 +}
 +</​sxh>​
 +
 +
 +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:
 +
 +
 +<sxh>
 + if (person.GenderType == GenderType.Male)) ​ {...Fine by me.}
 +
 +</​sxh>​
 +
 +And if an enum can be used in the place of GenderFK, it would not even be needed. Would be nice.