How to access Sitecore Database Programmatically

We know that Sitecore stores data in multiple Databases. To know more about Sitecore Databases check out Difference between Core, Master and Web Database in SitecoreSo How to access Sitecore Database Programmatically in C#? Let’s take a look at it in details.

How to access Sitecore Database Programmatically

From the web developer perspective, Master database is the most used DB to access the items  which is edited often in the content editor and the second most would be the web database or the live database.

Sitecore API to access Specific Database Programmatically

Sitecore database can be accessed through the Database class and you should obtain the reference to the Factory class as shown above.

If you need to access the web database then you could change the database parameter from “master” to “web”  while passing to the function.

Sitecore API to Fetch All the Available Database Names

GetDatabaseNames method returns a string array with list of Database Names added in /Configuration/Sitecore/Databases/Database.

Fetch the Current Context Database in Sitecore Programmatically

The above code will return the current context database. This is helpful when we are accessing the content from different environments and database. If we are using Page editor mode then most of the time we need items from Master database and if we accessing the live web page then we would require the items from web database.

Fetch all the Sitecore Databases Object into a list

This code will return all the databases objects which are configured in the configuration file.(/Configuration/Sitecore/Databases/Database)

Fetch the Database used by Content Editor in Sitecore

The ContentDatabase property will be empty when executing in the website context. Only content editors (such as the Content Manager) will normally support this property.

The link between contexts and databases is specified in the web.config below the section. For instance, the website context is defined as

The site definition for the Content Manager looks like this

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *