I am working on some C#.NET code that loads the entire set of taxonomy terms for a site. The current code is structured like this:
using (ClientContext context = new ClientContext(url))
{
TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(context);
context.Load(taxonomySession, ts => ts.TermStores);
context.ExecuteQuery();
TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
context.Load(termStore,
store => store.Groups.Include(
group => group.TermSets.Include(
termSet => termSet.Terms.Include(
term => term.Terms
)
)
)
);
context.ExecuteQuery();
foreach (TermGroup group in termStore.Groups)
{
foreach (TermSet termSet in group.TermSets)
{
LoadTerms(termSet.Terms, context);
}
}
}
void LoadTerms(TermCollection terms, ClientContext context)
{
foreach (Term term in terms)
{
TermCollection termCollection = term.Terms;
context.Load(termCollection,
tc => tc.Include(t => t.Terms)
);
context.ExecuteQuery();
LoadTerms(termCollection, context);
}
}
It makes two ExecuteQuery
calls for GetTaxonomySession
and GetDefaultSiteCollectionTermStore
, then it makes a bunch more calls to recursively load all the terms.
I am trying to reduce the number of ExecuteQuery
calls as much as possible. Is there any way to structure this code to recursively load the entire terms hierarchy in a single call?
Alternatively, is there any way to determine when a term has no children? A lot of the ExecuteQuery
calls are being made on terms that have no child terms, and return an empty result.