Search code examples
c#sitecoresitecore7

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


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.


Solution

  • 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