Reference - Content item query

This page provides information about the parameterization methods available for the Content item API. The methods allow you to adjust queries and limit which items are retrieved or specify which columns are loaded to improve performance, for example.

Throughout this page, the terms query and subquery are used with the following meaning:

  • Subquery – the selection created by a single ForContentType or ForContentTypes call, parameterized through the action delegate passed to the call.
  • Query – the combined result of all subqueries of a ContentItemQueryBuilder, parameterized through Parameters, InLanguage, and InWorkspaces.

ContentItemQueryBuilder methods

ForContentType

Retrieves all items of the specified content type. Generates a subquery that can be further configured. See Content query parameterization and ForContentType parameterization.

C#

var builder = new ContentItemQueryBuilder();

// Retrieves all content items of the 'Sample.Type' type
builder.ForContentType("Sample.Type");

Do not combine ForContentType with ForContentTypes, and do not register the same content type more than once through repeated ForContentType calls.

Content type field data is included in the result automatically. To include page data, use ForWebsite.

ForContentTypes

Retrieves all content items across all content types. Use the method’s parameterization to limit the selection to a subset of items.

Does not include content type field data and page data by default. Use WithContentTypeFields to include content type fields, and WithWebPageData or ForWebsite to include page data.

C#

var builder = new ContentItemQueryBuilder();

builder.ForContentTypes(subqueryParameters =>
{
    // Retrieves all items with the given reusable schema
    subqueryParameters.OfReusableSchema("PageMetadata");
});

Parameters

Specifies a set of parameters that apply to all items selected by individual subqueries. See Content query parameterization. Subqueries (created by ForContentType or ForContentTypes) are evaluated first, and only then is the parameterization from Parameters applied to their combined result. For example, TopN in a subquery combined with OrderBy in Parameters sorts only the records the subquery has already selected.

C#


var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type")
       .ForContentType("Sample.NewsRelease")
       .Parameters(queryParameters => queryParameters
           // Sorts all records retrieved by both subqueries
           // according to the 'ContentItemName' column
           .OrderBy("ContentItemName")
           // Takes the first 5 items of the sorted result
           .TopN(5));

InLanguage

Selects items from the specified language. The InLanguage method is applied to the result of all its preceding subqueries in a query. Do not call the method multiple times, only the last call takes effect.

The method allows you to specify the following parameters:

  • languageName – code name of the language as specified in the Languages application.
  • useLanguageFallbacks – dictates whether items that don’t have a variant in the requested language are retrieved in the closest language from the fallback chain. true by default. Set to false to restrict the result strictly to the requested language.
C#


var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type")
       .ForContentType("Sample.NewsRelease")
       // Selects only items that have an English variant, without language fallbacks
       .InLanguage("en", useLanguageFallbacks: false);

More advanced scenario including linked items:

C#


var builder = new ContentItemQueryBuilder();

builder.ForContentType("project.store", subqueryParameters =>
        {
            // Retrieves all linked items up to the maximum depth of 1
            subqueryParameters.WithLinkedItems(1);
        })
        // Selects only items from the English language
        .InLanguage("en");

You can see the order in which the query methods are evaluated in the following diagram:

InLanguage method used on ForContentType subquery with linked items

InWorkspaces

Selects items from the specified workspaces. Use workspace code names as specified in the Workspaces application. The InWorkspaces method is applied to the result of all its preceding subqueries in a query. Do not call the method multiple times, only the last call takes effect.

C#


var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type")
       .ForContentType("Sample.NewsRelease")
       // Selects only items from the WonkaFactory and Acme workspaces
       .InWorkspaces("WonkaFactory", "Acme");

Website channel pages are not scoped under workspaces. Combining this method with ForWebsite in a single query leads to an empty query result.

More advanced scenario including linked items:

C#


var builder = new ContentItemQueryBuilder();

builder.ForContentType("project.store", subqueryParameters =>
        {
            // Retrieves all linked items up to the maximum depth of 1
            subqueryParameters.WithLinkedItems(1);
        })
        // Selects only items from the WonkaFactory and Acme workspaces
        .InWorkspaces("WonkaFactory", "Acme");

You can see the order in which the query methods are evaluated in the following diagram:

InWorkspaces method used on ForContentType subquery with linked items

Content query parameterization

Columns

Limits the columns that are retrieved by the query. See Content item database structure.

If not specified, the query by default includes all columns from all selected content types.

C#

var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // Retrieves only the 'Title' and 'Content' columns from 'Sample.Type'
    subqueryParameters.Columns("Title", "Content");
});

If Columns is called multiple times for a content type, columns from all method calls are included.

Security considerations

Column names passed to the Columns method are not parameterized against SQL injection. Only use trusted, developer-controlled values. If the column names originate from external input, validate them against an allowlist. See Protect against SQL injection (the principles described for the ObjectQuery API apply).

The method also supports column aliasing:

C#

builder.ForContentType("Sample.Type1", subqueryParameters =>
{
    // Aliases 'Type1Title' as 'Title'
    subqueryParameters.Columns(QueryColumn.Alias("Type1Title", "Title"));
})
ForContentType("Sample.Type2", subqueryParameters =>
{
    // Aliases 'Type2Title' as 'Title'
    subqueryParameters.Columns(QueryColumn.Alias("Type2Title", "Title"));
})
// Orders both 'Type1' and 'Type2'
.Parameters(queryParameters => queryParameters.OrderBy("Title"));

UrlPathColumns

A specialized extension method that adds only the columns required for web page URL retrieval. This method helps optimize performance when you need only URL-related data.

When used with ForContentType, call the method inside the subquery parameterization action:

C#
UrlPathColumns usage

var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Page", subqueryParameters =>
{
    // Retrieves only columns required for URL path generation
    subqueryParameters.ForWebsite("SampleChannel")
                      .UrlPathColumns();
});

When used with ForContentTypes, call the method on the query-level Parameters:

C#
UrlPathColumns usage

var builder = new ContentItemQueryBuilder();

builder.ForContentTypes( /* subquery parameters... */)
       .Parameters(queryParameters =>
          // Retrieves only columns required for URL path generation
          queryParameters.UrlPathColumns()
       );

UrlPathColumns must be used in conjunction with ForWebsite or WithWebPageData. It automatically includes all columns required by the system to correctly resolve page URLs.

You can combine UrlPathColumns with additional Columns calls if you need URL columns in addition to other fields:

C#
UrlPathColumns usage

var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Page", subqueryParameters =>
{
    // Retrieves URL path columns plus the Title field
    subqueryParameters.ForWebsite("SampleChannel")
                     .UrlPathColumns()
                     .Columns("Title");
});

Offset

Offsets the records by the specified index (zero-based) and takes the next X items specified by fetch.

Must be used together with OrderBy, otherwise the pagination is not applied (as the system cannot guarantee a deterministic ordering of the returned results).

C#

var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // Takes the next 5 items starting from the 11th
    subqueryParameters.Offset(10, 5);
    subqueryParameters.OrderBy("ContentItemName");
});

Configure Offset at either the subquery level or the query level (Parameters), not both, and do not combine it with TopN in the same query.

IncludeTotalCount

Ensures that every retrieved item stores the total number of items, regardless of pagination applied by Offset.

C#

var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // Includes the total number of items
    subqueryParameters.IncludeTotalCount()
    // Takes the next 5 items starting from the 11th
    subqueryParameters.Offset(10, 5);
    subqueryParameters.OrderBy("ContentItemName");
});

After executing the query, use GetTotalCount on an item in the result to get the total number of items.

C#

var items = await queryExecutor.GetResult(builder, item => item);
int? totalItemCount = items.First().GetTotalCount();

Configure IncludeTotalCount at either the subquery level or the query level (Parameters), not both.

TopN

Limits the number of records fetched from the database. 

C#

var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // Takes the first 5 results from the selection
    subqueryParameters.TopN(5);
});

Do not combine TopN with Offset in the same query – they are two different ways to limit records and are not designed to be used together.

OrderBy

Allows ordering of the results based on the value of a specified column.

C#

var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // By default, items in the specified columns are sorted in ascending order
    subqueryParameters.OrderBy("ContentItemName");

    // You can parameterize the behavior by providing an instance of 'CMS.DataEngine.OrderByColumn'
    subqueryParameters.OrderBy(new OrderByColumn("ContentItemName", OrderDirection.Descending));
});

Security considerations

ORDER BY string expressions are not parameterized against SQL injection. Only use trusted, developer-controlled values. If ordering values originate from external input, validate them against an allowlist. See Protect against SQL injection (the principles described for the ObjectQuery API apply).

Where

Inserts an SQL WHERE clause into the query.

C#
WhereTrue

var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // Retrieves items that have the 'ShowInBanner' property set to true
    subqueryParameters.Where(where => where.WhereTrue("ShowInBanner"));
});
C#
WhereLike

var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // Multiple where operations are implicitly joined by AND
    subqueryParameters.Where(where => where.WhereLike("ColumnA", "value")
                                        .WhereLike("ColumnB", "value"));

    // OR has to be specified explicitly
    subqueryParameters.Where(where => where.WhereLike("ColumnA", "value")
                                        .Or()
                                        .WhereLike("ColumnB", "value"));
});
C#
WhereStartsWith

var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // Retrieves items whose name starts with with 'Apple'  
    subqueryParameters.Where(where => where.WhereStartsWith("ContentItemName", "Apple"));
});

The set of available Whereextensions matches the expressivity of the SQL WHERE syntax. This page provides examples of only a few of the available methods.

Security considerations

The value parameters (right-hand operands) in WHERE methods are automatically parameterized against SQL injection. However, columnName parameters (left-hand operands) are not parameterized. Only use trusted, developer-controlled values for column names. If column names originate from external input, validate them against an allowlist. See Protect against SQL injection (the principles described for the ObjectQuery API apply).

WhereContainsTags

Limits the query to content items that contain the specified tags.

C#
WhereContainsTags

// A collection of tags, e.g., obtained from a Tag selector
IEnumerable<Guid> tagIdentifiers;

var builder = new ContentItemQueryBuilder()
    .ForContentType(
        "Some.Type",
        subqueryParameters =>
            // Retrieves items with the specified tags
            subqueryParameters.Where(where =>
                where.WhereContainsTags("SomeTaxonomy", tagIdentifiers))
    ).InLanguage("en");

C#
WhereContainsTags

// A collection of tags, e.g., obtained from a Tag selector
IEnumerable<Guid> tagIdentifiers;
var tagCollection = await TagCollection.Create(tagIdentifiers);

var builder = new ContentItemQueryBuilder()
    .ForContentType(
        ArticlePage.CONTENT_TYPE_NAME,
        subqueryParameters =>
            // Retrieves items with the specified tags and any child tags
            subqueryParameters.Where(where =>
                where.WhereContainsTags("SomeTaxonomy", tagCollection))
    ).InLanguage("en");

ForContentType parameterization

Methods described in this section can only be called from within subqueries generated by a ContentItemBuilder.ForContentType call. 

ForWebsite

Configures the subquery to retrieve only pages from a specified website channel (no reusable content items are retrieved). It can only be called once per subquery. To retrieve both pages and reusable content items in a single query, use the ForContentTypes with WithWebPageData instead.

The ForWebsite method allows you to specify the following parameters:

  • websiteChannelName (required) – code name of the website channel from which the pages are retrieved.
  • pathMatch (optional) – a parameter of type PathMatch used to limit the retrieved pages only to a certain section of the website’s content tree. The parameter also accepts an array of PathMatch objects if you need to combine multiple path conditions, e.g., new[] { PathMatch.Children("/Articles"), PathMatch.SkipSection("/Articles/Coffee") }.
  • includeUrlPath (optional) – indicates if the URL path should be included in the retrieved data. true by default.
C#
ForWebsite

var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // Retrieves pages from the specified website channel
    subqueryParameters.ForWebsite(
                            websiteChannelName: "DancingGoatPages",
                            pathMatch: PathMatch.Children("/Articles"),
                            includeUrlPath: true);
});

See Retrieve page content for general guidance about retrieving page content, including the recommended ContentRetriever API.

ForWebsite makes page-specific fields available in the result, such as the URL, tree path, and identifiers like WebPageItemID and WebPageItemGUID. Without it, these fields are not included, and referencing them in Where, Columns, or OrderBy results in an invalid query.

WithLinkedItems

Configures the subquery to include linked content items recursively up to the specified depth.

C#
WithLinkedItems

var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // Retrieves all linked items up to the maximum depth of 2
    subqueryParameters.WithLinkedItems(2);
});

If the collection includes web page items and you want to use web page specific data (such as URL and tree path), specify the IncludeWebPageData option.

C#
IncludeWebPageData usage

var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // Retrieves all linked items up to the maximum depth of 2
    // including web page data of linked web page items
    subqueryParameters
        .WithLinkedItems(2, options => options.IncludeWebPageData());
});

To see how the query result is bound to a model class, check out WithLinkedItems mapping.

Linking

Retrieves all content items of the type specified in ForContentType that reference any of the content items from the provided collection in the given field. Enables loading data on-demand (lazily).

C#
Linking

var builder = new ContentItemQueryBuilder();

// Retrieves items of the 'project.staff' content type
builder.ForContentType("project.staff", subqueryParameters =>
{
    // Retrieves all content items of 'project.staff' type that reference any
    // of the items in 'managersCollection' from their 'ManagerField' field
    subqueryParameters.Linking("ManagerField", managersCollection);
});

Use at most one linking method per subquery (repeated calls are not supported). A subquery cannot combine Linking with LinkedFrom – it can retrieve links in only one direction.

For more information see Linking details.

LinkedFrom

Retrieves content items of the type specified in ForContentType that are linked from the given field of items in the provided collection with the given content type. Enables loading data on-demand (lazily).

C#
LinkedFrom

var builder = new ContentItemQueryBuilder();

// Retrieves items of the 'project.staff' content type
builder.ForContentType("project.staff", subqueryParameters =>
{
    // Items are retrieved for a collection of
    // 'project.store' items - 'storesCollection' - and the field 'StaffField'
    subqueryParameters.LinkedFrom("project.store", "StaffField", storesCollection);
});

For more information see LinkedFrom details.

LinkedFromSchemaField

Retrieves all content items of the type specified in ForContentType that are linked from a collection of items via a reusable schema field.

C#
LinkedFromSchemaField usage example

var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    subqueryParameters.LinkedFromSchemaField("SchemaFieldCodeName", contentItems);
});

For more information see LinkedFromSchemaField details.

SetUrlLanguageBehavior

Defines the behavior for the language slug of URL paths when web pages are retrieved in a fallback language. This method is relevant when requesting multilingual content (InLanguage) and retrieving page URL information (e.g., through methods like GetUrl(), often with ForWebsite or WithWebPageData).

It accepts a UrlLanguageBehavior enum value:

  • UrlLanguageBehavior.UseRequestedLanguage – When a page is served in a fallback language, its URL path is generated based on the language originally requested by the InLanguage method. For instance, if Spanish is requested and an English page is returned as a fallback, the URL path will still be structured as if it were a Spanish page (e.g., using URL prefixes as configured in the Languages application).
  • UrlLanguageBehavior.UseFallbackLanguage (Default) – When a page is served in a fallback language, its URL path is generated based on the language of the actual fallback content. In the example below, the URL path would be structured as an English page.
C#
Using SetUrlLanguageBehavior

// Assume 'builder' is an initialized ContentItemQueryBuilder

// Within ForContentType configuration:
builder.ForContentType("Sample.PageType", subqueryParameters =>
{
    subqueryParameters.ForWebsite("MyWebsiteChannel")
                      .SetUrlLanguageBehavior(UrlLanguageBehavior.UseRequestedLanguage)
})
// Requesting multilingual content
.InLanguage("spanish");

// After executing the query:
IEnumerable<SamplePageType> pages = await executor.GetMappedWebPageResult<SamplePageType>(builder);
foreach (var page in pages)
{
    // If 'page' is an English fallback for a Spanish request, 
    // its url will be in the format:
    //
    // '/<spanishLanguageName>/my-page-slug'
    //
    // due to 'UseRequestedLanguage'.
    WebPageUrl url = page.GetUrl();
}

ForContentTypes parameterization

Methods described in this section can only be called from within subqueries generated by a ContentItemBuilder.ForContentTypes call.

OfContentType

Selects items with the specified content types.

C#
Retrieve based on content type

var builder = new ContentItemQueryBuilder();

builder.ForContentTypes(subqueryParameters =>
{  
    // Retrieves items of the 'Acme.Article', 'Acme.Blog' content types
    subqueryParameters.OfContentType("Acme.Article", "Acme.Blog");
});

Do not combine OfContentType with OfReusableSchema in the same subquery.

OfReusableSchema

Selects items with the specified reusable field schema.

C#
Retrieve based on reusable field schema

var builder = new ContentItemQueryBuilder();

builder.ForContentTypes(subqueryParameters =>
{  
    // Retrieves items with the 'PageMetadata' reusable field schema
    subqueryParameters.OfReusableSchema("PageMetadata");
});

Call OfReusableSchema only once per subquery (repeated calls are not supported), and do not combine it with OfContentType.

ForWebsite

Provides multiple overloads that can:

  • select all pages in the system
  • select pages based on their ID, GUID, or code names
  • select pages from specific website channels and paths
C#
Retrieve web page items

var builder = new ContentItemQueryBuilder();

builder.ForContentTypes(subqueryParameters =>
{
    // Calls are mutually exclusive
    // Shown to demonstrate available overloads

    // Retrieves all pages in the system
    subqueryParameters.ForWebsite();

    // Retrieves pages with the provided GUIDs
    // (e.g., from the 'Page selector' component)
    subqueryParameters.ForWebsite(webPageGuids);

    // Retrieves all pages under the 'Acme' channel and 'Articles' page path
    subqueryParameters.ForWebsite(
            websiteChannelName: "Acme",
            pathMatch: PathMatch.Children("/Articles"));
});

Each overload also provides the optional includeUrlPath path parameter. true by default, it indicates whether web page URL data should be included in the query.

ForWebsite includes page-specific fields (such as URL and tree path) in the result and limits the result to page content types. It cannot be called more than once per subquery, and cannot be combined with WithWebPageData in the same subquery (both include page data). If you want to retrieve pages and reusable content items in a single query, use WithWebPageData instead.

Page-specific fields, such as the page URL, tree path, page order, and identifiers like WebPageItemID and WebPageItemGUID, become available once the query includes page data. Referencing them in Columns, Where, or OrderBy without including page data results in an invalid query. The following example retrieves pages of a specific content type and filters them by their WebPageItemID:

C#
Filter pages by WebPageItemID

// A collection of page identifiers
IEnumerable<int> webPageItemIds;

var builder = new ContentItemQueryBuilder();

builder.ForContentTypes(subqueryParameters =>
{
    subqueryParameters.OfContentType("Acme.ArticlePage")
                      // Includes page data (do not also call WithWebPageData)
                      .ForWebsite()
                      .WithContentTypeFields();
})
  .Parameters(queryParameters =>
      queryParameters.Where(where =>
          // Keeps only pages whose 'WebPageItemID' is in the 'webPageItemIds' collection
          where.WhereIn(nameof(WebPageFields.WebPageItemID), webPageItemIds)));

WithContentTypeFields

By default, the result returned by ForContentTypes contains content item metadata (CMS_ContentItem table Content item database structure) and reusable field schema data. WithContentTypeFields also adds content type-specific fields to the result.

You must call WithContentTypeFields to reference content type-specific fields in Columns, Where, or OrderBy. Referencing such fields without it produces an invalid query.

C#
WithContentTypeFields example

var builder = new ContentItemQueryBuilder();

builder.ForContentTypes(subqueryParameters =>
{
    // Retrieves items with the 'PageMetadata' reusable field schema
    // and includes content-type specific fields in the result
    subqueryParameters.OfReusableSchema("PageMetadata")
                      .WithContentTypeFields();
});

WithWebPageData

By default, the result returned by ForContentTypes contains content item metadata (CMS_ContentItem table Content item database structure) and reusable field schema data. WithWebPageData also adds website content-specific fields (such as URL and tree path) to the result.

C#
WithWebPageData example

var builder = new ContentItemQueryBuilder();

builder.ForContentTypes(subqueryParameters =>
{
    // Retrieves items with the 'PageMetadata' reusable field schema
    // and includes web page specific fields in the result
    subqueryParameters.OfReusableSchema("PageMetadata")
                      .WithWebPageData();
});

WithWebPageData includes page fields without limiting the result to page content types, so a single query can return a mix of pages and reusable content items. Do not call it more than once per subquery, and do not combine it with ForWebsite in the same subquery – both include page data, which results in an invalid query.

WithLinkedItems

Configures the subquery to include linked content items recursively up to the specified depth. The parameterization behaves identically to its alternative in ForContentType.

C#
WithLinkedItems usage

var builder = new ContentItemQueryBuilder();

builder.ForContentTypes(subqueryParameters =>
{
    // Retrieves all linked items up to the maximum depth of 2
    subqueryParameters
        .OfContentType(Article.CONTENT_TYPE_NAME)
        .WithLinkedItems(2);
});

If the collection of linked items contains web page items, you need to specify the IncludeWebPageData option to include web page specific data (such as URL and tree path) of the web page items:

C#
IncludeWebPageData usage

var builder = new ContentItemQueryBuilder();

builder.ForContentTypes(subqueryParameters =>
{
    // Retrieves all linked items up to the maximum depth of 2
    // including web page data of linked web page items
    subqueryParameters
        .OfContentType(Article.CONTENT_TYPE_NAME)
        .WithLinkedItems(2, options => options.IncludeWebPageData());
});

To see how the query result is bound to a model class, check out WithLinkedItems mapping.

Linking

The method behaves identically to ForContentType.Linking, with the following exceptions:

  • You need to specify the name of the content type whose items you want to retrieve, in addition to the field used to link the items. This is necessary to prevent ambiguities in case the searched content types contain identical field names.
  • The usage is limited to one Linking call for each ForContentTypes subquery, and cannot be combined with LinkedFrom or LinkedFromSchemaField (a subquery retrieves links in only one direction).
C#
ForContentTypes.Linking usage

var builder = new ContentItemQueryBuilder();
builder.ForContentTypes(subqueryParameters =>
{
    // Retrieves items of the 'project.staff' type that link to
    // any of the content items in 'managersCollection' via their 'ManagerField' field
    subqueryParameters.Linking("project.staff", "ManagerField", managersCollection);
});

For more information see Linking details.

LinkedFrom

The behavior is identical to ForContentType.LinkedFrom, with the only difference being that you cannot chain multiple calls within a single subquery. It also cannot be combined with Linking or LinkingSchemaField in the same subquery.

For more information see LinkedFrom details.

LinkingSchemaField

Retrieves all content items that link to a collection of items via the specified reusable schema field. LinkedFromSchemaField complements this method by retrieving links from the opposite direction.

Use at most one linking method per subquery (repeated calls are not supported), and do not combine LinkingSchemaField with LinkedFrom or LinkedFromSchemaField in the same subquery.

C#
LinkingSchemaField method usage

var imageIdentifiers = new List<int>() { 1, 2, 3 };

var builder = new ContentItemQueryBuilder().ForContentTypes(subqueryParameters =>
{
    subqueryParameters.LinkingSchemaField("ProductImage", imageIdentifiers);
});

For more information see LinkingSchemaField details.

LinkedFromSchemaField

Retrieves all content items that are linked from a collection of items via a reusable schema field. LinkingSchemaField complements this method by retrieving links from the opposite direction.

Use at most one linking method per subquery (repeated calls are not supported), and do not combine LinkedFromSchemaField with Linking or LinkingSchemaField in the same subquery.

C#
LinkedFromSchemaField method usage

var builder = new ContentItemQueryBuilder().ForContentTypes(subqueryParameters =>
{
    subqueryParameters.LinkedFromSchemaField("ProductImage", productIdentifiers);
});

For more information see LinkedFromSchemaField details.

InSmartFolder

Retrieves content items that fulfill the filter conditions of the specified smart folder. This allows content editors to control which items are retrieved directly in the Content hub UI, without needing to adjust the code.

The smart folder can be specified by its ID, GUID, or code name. You can get the smart folder GUID from a field using the Smart folder selector UI form component. You can also find the identifiers of smart folders in the Content hub application – expand the menu actions of a folder and select Properties.

C#
InSmartFolder method usage

var builder = new ContentItemQueryBuilder();

// Retrieves content items from the specified smart folder
builder.ForContentTypes(subqueryParameters => subqueryParameters.InSmartFolder(smartFolderGuid));

The InSmartFolder parameterization causes the subquery to return an empty result if the specified smart folder:

  • Doesn’t exist
  • Doesn’t have dynamic content delivery enabled
  • Has invalid filter conditions (for example if a tag saved in the Taxonomy filter option was later deleted)

The following scenarios are unsupported and result in an exception:

  • Using multiple InSmartFolder calls for a single subquery
  • Combining InSmartFolder with ForWebsiteparameterization (smart folders are only supported for reusable content items, not pages)

If you need to ensure that only items of one specific content type are retrieved (regardless of the smart folder’s filter condition), add OfContentType to the parameterization.

C#
InSmartFolder usage for a specific content type

var builder = new ContentItemQueryBuilder();

// Retrieves items of one specific content type from a smart folder
builder.ForContentTypes(subqueryParameters =>
{
    subqueryParameters.InSmartFolder(smartFolderGuid)
                      .OfContentType("Sample.Type");
});

SetUrlLanguageBehavior

Defines the behavior for the language of URL paths when web pages are retrieved in a fallback language. This method is particularly relevant when using InLanguage and retrieving page URL information (e.g., through methods like GetUrl() after ensuring necessary columns are loaded, often with ForWebsite or WithWebPageData).

It accepts a UrlLanguageBehavior enum value:

  • UrlLanguageBehavior.UseRequestedLanguage – When a page is served in a fallback language, its URL path is generated based on the language originally requested by the InLanguage method. For instance, if Spanish is requested and an English page is returned as a fallback, the URL path will still be structured as if it were a Spanish page (e.g., using URL prefixes as configured in the Languages application).
  • UrlLanguageBehavior.UseFallbackLanguage (Default) – When a page is served in a fallback language, its URL path is generated based on the language of the actual fallback content. In the example below, the URL path would be structured as an English page.
C#
Using SetUrlLanguageBehavior

var builder = new ContentItemQueryBuilder();

builder.ForContentTypes(subqueryParameters =>
{
    subqueryParameters.ForWebsite("MyWebsiteChannel") // Retrieves pages, including their page data
                      .SetUrlLanguageBehavior(UrlLanguageBehavior.UseRequestedLanguage)
})
.InLanguage("spanish"); // Requesting content in Spanish

// After executing the query:
IEnumerable<SamplePageType> pages = await executor.GetMappedWebPageResult<SamplePageType>(builder);
foreach (var page in pages)
{
    // If 'page' is an English fallback for a Spanish request, 
    // its url will be in the format:
    //
    // '/<spanishLanguageName>/my-page-slug'
    //
    // due to 'UseRequestedLanguage'.
    WebPageUrl url = page.GetUrl();

}

Where conditions

Where parameterization can be added to a query containing ForContentTypes subqueries using Parameters.

C#
Adding Where conditions

var builder = new ContentItemQueryBuilder();
builder.ForContentTypes(subqueryParameters =>
{
    // ...
}).Parameters(queryParameters =>
{
    queryParameters.Where(where => where) //...
});

Security considerations

The value parameters (right-hand operands) in WHERE conditions are automatically parameterized against SQL injection. However, columnName parameters (left-hand operands) are not parameterized. Only use trusted, developer-controlled values for column names. If column names originate from external input, validate them against an allowlist. See Protect against SQL injection (the principles described for the ObjectQuery API apply).

Method details

Methods described in this section can only be called from within subqueries generated by a ContentItemBuilder.ForContentTypes call or a ContentItemBuilder.ForContentType call.

WithLinkedItems

IContentQueryExecutor.GetMappedResult, IContentQueryExecutor.GetMappedWebPageResult, or using the provided IContentQueryModelTypeMapper automatically binds the linked content item hierarchy to the specified model.

C#

IEnumerable<ModelClass> data =
            queryExecutor.GetMappedResult<ModelClass>(builder);

When mapping the data manually, use GetLinkedItems on the result to get the next level of references. This can be repeated up until the specified recursion level.

C#

var data = queryExecutor.GetResult<ContentItemDto>(builder, resultSelector);

private ContentItemDto resultSelector(IContentQueryDataContainer itemData)
{
    var item = new ContentItemDto
    {
        Title = itemData.GetValue<string>("Title"),
        Text = itemData.GetValue<string>("Text"),

        // Retrieves first-level linked items from the 'Author' field
        AuthorName = itemData.GetLinkedItems("Author").First()
                                .GetValue<string>("Name");

        // Retrieves second-level linked items from the 'Author' field
        AuthorProfileBlurb = 
            itemData.GetLinkedItems("Author").First()
                    .GetLinkedItems("Profile").First()
                    .GetValue<string>("ProfileBlurb");
    };

    return item;
}

Linking

Retrieves all content items which reference any of the content items from the provided collection in the specified field. Enables loading data on-demand (lazily).

The following diagram illustrates the behavior on a simple content model:

Linking usage visualization

Combining this method with LinkedFrom in a single subquery is not supported.

The method can also be used together with WithLinkedItems. For example:

C#
Linking and WithLinkedItems

var builder = new ContentItemQueryBuilder();

// Retrieves items of the 'project.staff' content type
builder.ForContentType("project.staff", subqueryParameters =>
{
    // Retrieves all items of 'project.staff' type that reference any of the
    // items in 'managersCollection' from their 'ManagerField' together with
    // all second-level references for the selected 'project.staff' items
    subqueryParameters.Linking("ManagerField", managersCollection)
                    .WithLinkedItems(2);
});

Linking usage visualization

The collection of items for which to retrieve references must implement the IContentItemIdentifier interface. The interface ensures fields required by each data model that wants to leverage this method.  The fields must be bound to the model during model binding within ContentQueryExecutor.GetResult.

Generated content type classes already implement IContentItemIdentifier via the SystemFields property. The following approach applies for custom model classes.

C#
IContentItemIdentifier fields in custom model classes

var data = queryExecutor.GetResult<ContentItemDto>(builder, resultSelector);

ManagerDto resultSelector(IContentQueryDataContainer itemData)
{
    var item = new ManagerDto
    {
        // Binds fields required by 'Linking'
        ContentItemID = itemData.ContentItemID,
        ContentItemLanguageID = itemData.ContentItemDataContentLanguageID,
        // other fields...
    };

    return item;
}

// Example custom model class binding content items of the 'Manager' content type
class ManagerDto : IContentItemIdentifier
{
    public int ContentItemID { get; }
    public int ContentLanguageID { get; }
    public IEnumerable<ContentItemReference> PictureField { get; }
    public IEnumerable<ContentItemReference> AwardsField { get; }
}

LinkedFrom

Retrieves content items of a specific type linked from the given field in the provided collection. Enables loading data on-demand (lazily).

The following diagram illustrates the behavior on a simple content model. Red arrows trace query evaluation:

LinkedFrom usage visualization

Combining this method with Linking in a single subquery is not supported.

The method can also be used together with WithLinkedItems. For example:

C#
Linked from and WithLinkedItems

var builder = new ContentItemQueryBuilder();

// Retrieves items of the 'project.staff' content type
builder.ForContentType("project.staff", subqueryParameters =>
{  
    // Items are retrieved for a collection of 'project.store' items and the field 'StaffField'
    // together with all first-level references for the selected 'project.staff' items
    subqueryParameters.LinkedFrom("project.store", "StaffField", storesCollection)
                        .WithLinkedItems(1);
});

LinkedFrom usage visualization

The collection of items for which to retrieve references must implement the IContentItemIdentifier interface. The interface ensures fields required by each data model that wants to leverage this method. The fields must be bound to the model during model binding within ContentQueryExecutor.GetResult.

Generated content type classes by default implement IContentItemIdentifier via the SystemFields property. The following approach applies for custom model classes.

C#
IContentItemIdentifier fields in custom model classes

var data = queryExecutor.GetResult<ContentItemDto>(builder, resultSelector);

StoreDto resultSelector(IContentQueryDataContainer itemData)
{
    var item = new StoreDto
    {
        // Binds fields required by `LinkedFrom`
        ContentItemID = itemData.ContentItemID,
        ContentItemLanguageID = itemData.ContentItemDataContentLanguageID,
        // other fields...
    };

    return item;
}

// Example custom model class binding content items of the 'Store' content type
class StoreDto : IContentItemIdentifier
{
    public int ContentItemID { get; }
    public int ContentLanguageID { get; }
    public IEnumerable<ContentItemReference> StaffField { get; }
    public IEnumerable<ContentItemReference> ReferenceField { get; }
    public IEnumerable<ContentItemReference> FaqField { get; }
}

LinkingSchemaField

This method can only be called from within subqueries generated by a ContentItemBuilder.ForContentTypes call.

Retrieves all content items that link to a collection of items via the specified reusable schema field. LinkedFromSchemaField complements this method by retrieving links from the opposite direction.

See the following diagram for an illustration of the method’s behavior on a simplified content model. The subquery retrieves all content items that link to the images from imageIdentifiers via the ProductImage reusable schema field. Red arrows trace the subquery evaluation:

LinkinkSchemaField method demonstration

In the diagram above, the method is called with the following parameters:

  • "ProductImage" – the code name of a field that belongs to a reusable field schema. Reusable schema field code names must be unique across the system, it’s therefore sufficient to target fields directly.
  • imageIdentifiers – IDs of content items with the Image content type.

LinkedFromSchemaField

Retrieves all content items that are linked from a collection of items via a reusable schema field. LinkingSchemaField complements this method by retrieving links from the opposite direction.

See the following diagram for an illustration of the method’s behavior on a simplified content model. The subquery retrieves all Image content items that are linked from productIdentifiers via the ProductImage reusable schema field. Red arrows trace the subquery evaluation:

LinkedFromSchemaField method demonstration

In the diagram above, the method is called with the following parameters:

  • "ProductImage" – the code name of a field that belongs to a reusable field schema. Reusable schema field code names are unique and can be targeted directly without specifying the corresponding schema.
  • productIdentifiers – a collection of content items from content types using the ProductFields reusable field schema.

The collection of items for which to retrieve references must implement the IContentItemIdentifier interface. The interface ensures fields required by each data model that wants to leverage this method.

Generated content type classes by default implement IContentItemIdentifier via the SystemFields property.

IContentQueryExecutor configuration

Apart from configuring the query itself, you can also fine tune its execution. You can do so by setting the properties of the ContentQueryExecutionOptions attribute and providing it to the IContentQueryExecutor interface.

Property

Description

ForPreview

If set to true, the query executor retrieves the queried items in their latest available version, regardless of their workflow state. Otherwise, the latest published version is retrieved.

Default value: false.

IncludeSecuredItems

If set to true, the query executor retrieves all items according to the query, including secured items. Otherwise, only items that are not secured are included in the query.

Default value: false.

The ContentRetriever API exposes equivalent settings through its parameter objects. For examples of how these settings affect data retrieval, see Page security configuration and Retrieve pages for preview.