How to store database constants in the application code?


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).

How to store database constants in the application code?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s