2
votes

I've been struggling with this Sitecore query code. All items are published, the query works in XPath Builder, but it always returns 0 results in the code behind. I copied this from code samples that no one else complained about and still get no results. I tried appending with "query:" but it throws a syntax error.

string query = "/sitecore/content/ShrinersHospital2/CareAndTreatment//*[@@templatename = 'CareAndTreatmentType' and @TreatmentType = '{ECDBE944-99DE-4347-8FA2-6613FA85402C}']"; 

Item[] items = Sitecore.Context.Database.SelectItems(query); 
2

2 Answers

5
votes

This particular issue has to do with publishing issues. The queried item had it's template modified and the Incremental Publish failed to push the changes correctly. A Smart Publish made the code start working.

I was also informed that when something like this happens I should test on both databases using code as follows:

Database master = Factory.GetDatabase("master"); 
master.SelectItems(query); 

Database web = Factory.GetDatabase("web"); 
web.SelectItems(query); 
3
votes

I had the same problem and found the following solution:

   Item[] items = Sitecore.Context.Database.SelectItems(query);

This won't work since your code is executed in the (current) context. And code is executed in the path

/sitecore/content/ShrinersHospital2/CareAndTreatment

With your query above you tell sitecore to search from the path

/sitecore/content/ShrinersHospital2/CareAndTreatment/sitecore/content/ShrinersHospital2/CareAndTreatment

which will return 0 items as result, because the path does not exist.

Try the following query:

string query = "//*[@@templatename = 'CareAndTreatmentType' and @TreatmentType = '{ECDBE944-99DE-4347-8FA2-6613FA85402C}']"; 
Item[] items = Sitecore.Context.Database.SelectItems(query);

When you switch your database to "web", you do not have a context and your "starting" path is /. Then the code below returns items with your query, because the path exists

/sitecore/content/ShrinersHospital2/CareAndTreatment

string query = "/sitecore/content/ShrinersHospital2/CareAndTreatment//*[@@templatename = 'CareAndTreatmentType' and @TreatmentType = '{ECDBE944-99DE-4347-8FA2-6613FA85402C}']"; 
var database = Sitecore.Configuration.Factory.GetDatabase("web");
items = database.SelectItems(query);