Best practice for loading and using dictionary items?
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 pul开发者_开发问答l these categories once as they never change during a given session. What's the best way to do this?
Do whatever I am doing, but store it as a Application variable?
Hard code the categories in the code, and do away with the database?
Store the categories in a session variable? And call the DB only if the session is empty?
Or something else?
I'm just curious to know what the best-practice is for doing such things.
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.
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.
精彩评论