CSOM chain includes to retrieve all labels for all terms

CSOM chain includes to retrieve all labels for all terms

When working with CSOM there are quite a few samples out there. Most of these samples are pretty straight forward and can help you get up to speed when working with the CSOM model. Yet I couldn’t find any samples on how to load all the terms for all termsets. Especially when working with multiple languages. As in that case it would make sense to retrieve all labels for the termset.

When working with the CSOM model you can use the Include() method. Using that method you can specify what you should include. As with a normal load you will include only the default properties. Using the Include you can easily identify that you would like to load a termset and all it child terms.

Web ctxWeb = context.Web;
context.Load(ctxWeb, w => w.Language);
context.ExecuteQuery();

TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(context);
TermSetCollection termset = taxonomySession.GetTermSetsByName("sampletermset", (int)ctxWeb.Language);

context.Load(termset, termSetsArg => termSetsArg.Include(
    termSetArg => termSetArg.Terms
    )
);

context.ExecuteQuery();

However you can chain these Include methods as well. So instead executequery multiple times you can create a single load and chain the includes. So that with a single execution you can retrieve everything you require.

To do so you can use the same include as before, but add an extra argument with another include. In that second include you can specify what properties you require for that object. As you can see in the following snippet it is fairly easy.

Web ctxWeb = context.Web;
context.Load(ctxWeb, w => w.Language);
context.ExecuteQuery();

TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(context);
TermSetCollection termset = taxonomySession.GetTermSetsByName("sampletermset", (int)ctxWeb.Language);

context.Load(termset, termSetsArg => termSetsArg.Include(
    termSetArg => termSetArg.Terms,
    termSetArg => termSetArg.Terms.Include(
            t => t.Labels
        )
    )
);

context.ExecuteQuery();

if (termset != null && termset.Count != 0) {
    ts = termset[0];
}

I was a bit surprised that there weren’t any samples to chain the includes, but in the end it is fairly easy. You can use the same approach for any property that is not loaded by default. So it is a quite powerful way to minimize the amount of executes.

Leave a Reply