If you are a database application developer you often face the problem of using database constants in your application code. I would like to present you a way how to use such constants and avoid hard-coding data-table primary key values.
For further considerations, let’s assume that we have an Employee class (mapping Employee database table). Employee class has then a field Profession (which is of Profession type and represents meta-table Profession in the database):
public class Profession { // stores database key value public virtual Int32 Id { get; set; } // a field code that identifies the value in the application public virtual String FieldCode { get; set; } // descriptive name of the profession public virtual String Name { get; set; } } /* **************** */ public class Employee { // profession of the employee public virtual Profession { get; set; } }
You may notice an additional propertyFieldCode in the Profession class. This field will connect database record with application logic. Let’s create a static class that will store constant strings representing field codes of professions that interest us:
public static class ProfessionCodes { public const String Driver = "DRIVER"; public const String Secretary = "SECRETARY" }
Then anytime we need to write some code specific for a given profession we will use the FieldCode and our ProfessionCodes class:
Employee emp = GetEmployee(); // ... some code here if (emp.Profession.FieldCode.Equals(ProfessionCodes.Driver) { // logic specific to the driver profession }
One caveat here: all classes that have a FieldCode property should be stored in second level cache. It’s because anytime you try to access a property different than a primary key a whole object must be retrieved from the database by the ORM (and thus at least one SELECT is performed).