Sitecore.Context.Database.GetItem() not working in sitecore events

4.9k views Asked by At

I am using Sitecore 7.0. Visual Studio 2013. I want to create an item's child in Sitecore using event Handler. So whenever an item is created, its child automatically added. For this I wrote an eventHandler on "item:added" event.

But I am getting NullReferenceException exception "Exception Details: System.NullReferenceException: Object reference not set to an instance of an object."

I figure out that Database.GetItem() method is not working in Sitecore Events.

Item entryFolderItem = Sitecore.Context.Database.GetItem("/sitecore/content/Site Config/Configuration/Entry Folders Structure");

The above item exist in sitecore and I have also tried with ID. But still I get the same error.

I also tried the same code on event item:saved but still I get the same error.

Any suggestion for this problem!!

By the way here you can find a nice article on events.

2

There are 2 answers

0
Mark Cassidy On BEST ANSWER

Don't assume you can get a context. Besides, going for context database would be wrong, so would be going for a hardcoded "master" database.

When you extract the Item from EventArgs, use the .Database definition from there to perform your operations.

Item eventItem = eventArgs.Parameters[0] as Item;
Database db = eventItem.Database;

More information here: https://community.sitecore.net/technical_blogs/b/sitecorejohn_blog/posts/repost-intercepting-item-updates-with-sitecore

0
Kamran On

I was trying to access the Sitecore.Context.Database and it was not working. Then I tried with MasterDB

     Database masterDb = Sitecore.Configuration.Factory.GetDatabase("master");
   Item entryFolderItem = masterDb.Items["/sitecore/content/Site Config/Configuration/Entry Folders Structure"]

And it worked out successfully.