Issue with getting database via Sitecore API

api, database, sitecore

Solution

A common way you will see people get a specific database is:

Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");

This is equivalent to `Sitecore.Data.Database.GetDatabase("master")`.

When you call either of these methods it will first check the cache for the database. If not found it will build up the database with all of the configuration values within the config file via reflection. Once the database is created it will be placed in the cache for future use.

When you use the constructor on the database it is simply creating a rather empty database object. I am rather suprised to hear it was working at all when you used this method.

The proper approach to get a specific database would be to use:

Sitecore.Configuration.Factory.GetDatabase("master");
// or
Sitecore.Data.Database.GetDatabase("master");

If you are looking to get the database used with the current request (aka context database) you can use `Sitecore.Context.Database`. You can also use `Sitecore.Context.ContentDatabase`.

Problem

We noticed a slight oddity in the Sitecore API code. The code is below for your reference. The code is trying to get a database by doing `new Database(database)`. But randomly it was failing. This code worked for a while with `Database db = new Database(database);` but started failing randomly yesterday. When we changed the code to `Database db = Database.GetDatabase(database);`, the code started working again. What is the difference between the two approaches and what is recommended by Sitecore? I've seen this happen twice now - multiple times in production and a couple of times in my development environment. ``` public static void DeleteItem(string id, stringdatabase) { //get the database Database db = new Database(database); //get the item item = db.GetItem(new ID(id)); if (item != null) { using(new Sitecore.SecurityModel.SecurityDisabler())| { //delete the item item.Delete(); } } } ```

Original source