When we start exploring the Sitecore, and try few code snippets from the internet, they work fine for us on our development machine. But we always need to make sure we follow the best practices.
In many cases, I have seen developers hard coding the database to get the item details & then fix it after code review. So in this blog, Ill explain how and why we access the database in a particular way.
If you have googled about accessing Sitecore database through code then you will know that we have 3 ways to do it:
- Sitecore.Data.Database db = Sitecore.Configuration.Factory.GetDatabase(“master”);
- Sitecore.Data.Database db = Sitecore.Data.Database.GetDatabase(“master”);
- Sitecore.Data.Database db = Sitecore.Context.Database;
All of the above statement works fine in accessing the database but if you see the first 2 are hardcoded or tightly coupled with database we are trying to access.
Imagine you have a code where you access the database and then extract the item details. If you use the first 2 statements for this scenario then it will work fine on your development machine, also it will work as expected on CM site. But when you try to access same piece of code on CD site, it will break because we disable master DB in the CD environment.
Another work around which developers used to use here is to keep the DB name in App settings and configure “master” for CM & “web” for CD environment.
In the latest implementations, we use the third statement. The Context changes automatically based on the environment you are accessing. If we try to access the CM site then the Context Database is Master & the same changes to Web when we switch to CD environment. This is recommended practice and keeps the code clean.
Now you must be wondering, in which scenario we should go for first 2 statements. Consider you want to create items programatically then we hardcode the database to Master and further logic can be to publish it or the Content Authors verify it in Content tree and publish it. In case the piece of code is accidentally deployed on CD environment then the items won’t be created either in Master or Web database because master database is not accessible on CD and we have hardcoded the Master DB in our piece of Code.
Hope the above explanation helps you to better understand how to access Sitecore database in the best way possible.
Thank you… Keep Learning.. Keep Sitecoring 🙂