views:

74

answers:

2

Say I have some 10 "categories" that I need to reference in a web app. Currently I'm storing these categories in the DB and am retrieving them (category name and id) during pageload in my basepage, storing them in a hashtable and then using the hashtable to reference the categories. I realized that the DB call is being made during each pageload. I only need to pull these categories once as they never change during a given session. What's the best way to do this?

  1. Do whatever I am doing, but store it as a Application variable?

  2. Hard code the categories in the code, and do away with the database?

  3. Store the categories in a session variable? And call the DB only if the session is empty?

  4. Or something else?

I'm just curious to know what the best-practice is for doing such things.

+2  A: 

If the categories are user dependent then I'd store them in the Session variable; otherwise I'd use the ASP.NET Caching functionality (or preferred distributed caching). This allows you to avoid hitting the database whilst being able to control how long the categories should be cached for.

Paul Mason
Thanks. Actually to be honest these categories never change--they are always the same for the life of the application. Unless there's a change in the business requirement...Do you still recommend caching? Would it be ugly to make the categories as enums?
Prabhu
It really depends on how many objects rely on a relationship with your category object. If the category is used in one place, and in one place only (which isn't reported against) then I'd definitely consider simply using a smallint and an enum, however if it is used against multiple objects or is used in SQL reporting services for example then I'd keep it in the database. Personally, enums have their place; however I'm not sure this is one of them :)
Paul Mason
A: 

Calling the database is not always as expensive as it seems, a typical website makes dozens of calls to the DB on each pageload. But if it becomes troublesome in terms of performance, consider using an ORM solution. The excellent open source NHibernate comes to mind, which is the "de facto" standard for mapping databases to classes and objects. Beyond the mapping, it automatically provides two levels of caching and connection pooling. Without too much trouble, your website outperforms any other's by a landslide.

The downside of using an ORM? To many people, it is considered a rather steep learning curve. If you want to read into this, make sure to pay a visit to the NHibernate Best Practices. A tough read at first, but definitely worthwhile.

If you combine NHibernate with FluentNHibernate, it becomes a breeze to use.

Abel