What Sitecore database am I in?

In Sitecore development code reviews, one of the issues I see most consistently is how you choose to access the Content or Context database. When most of us develop on a local instance of Sitecore, we work on a single Sitecore instance, which means we have access to a “master” database that has every version of every item and a “web” database that contains the currently published content.  Here are some rules around how you access these databases:

1. You almost never want to specifically reference the master, unless you are developing editing functionality for the Sitecore back-end or importing content.

//You probably don't want to be doing this
Sitecore.Data.Database master =  Sitecore.Configuration.Factory.GetDatabase("master");

There are a number of good reasons you don’t want to do this. First, you are by-passing the publishing process when you reference the master database. Sitecore makes all appropriate content available in the web database and you should use that. Another important reason is that the Security Hardening Guide for Sitecore suggests removing the “master” connection string on content delivery servers, which will cause your code to error if you are referencing it.

2. If you are sure that you actually want to reference the master database, you are still better off not referring it to it as master, but instead asking Sitecore to give you the correct database. The Sitecore context has a property called ContentDatabase that will give you the master database in a more flexible way.

Sitecore.Data.Database contentDatabase =  Sitecore.Context.ContentDatabase;

3. When you are accessing the web database, which you should be doing most of the time, you should not specifically reference it by the name “web” either. The name of the database is actually configurable and may be different in different environments. The Sitecore Context has an additional property

//don't do this
Sitecore.Data.Database database =  Sitecore.Configuration.Factory.GetDatabase("web");

//do this
Sitecore.Data.Database database = Sitecore.Context.Database;
%d bloggers like this: