Reference - Content item query

This page provides information about the parametrization 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.

ContentItemQueryBuilder methods

Method

Description

ForContentType

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


var builder = new ContentItemQueryBuilder();

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

ForContentTypes

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

Does not include content type field data by default. Use WithContentTypeFields to include it.


var builder = new ContentItemQueryBuilder();

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

Parameters

Specifies a set of parameters that apply to all items selected by individual subqueries. See Content query parameterization.



var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type")
       .ForContentType("Sample.NewsRelease")
// Sorts all records according to the 'ContentItemName' column
       .Parameters(globalParams => globalParams.OrderBy("ContentItemName"))

InLanguage

Selects items from the specified language. Use language code name as specified in the Languages application.



var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type")
       .ForContentType("Sample.NewsRelease")
// Selects only items from the English language
       .InLanguage("en");

> Back to the top

Content query parameterization

Method

Description

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.


var builder = new ContentItemQueryBuilder();

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

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

The method also supports column aliasing:


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(globalParameters => globalParameters.OrderBy("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).


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");
});

IncludeTotalCount

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


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.


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

TopN

Limits the number of records fetched from the database. 


var builder = new ContentItemQueryBuilder();

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

OrderBy

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


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));
});

Where

Inserts an SQL WHERE clause into the query.

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"));
});
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"));
});
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.

WhereContainsTags

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

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");

WhereContainsTags

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

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

> Back to the top

ForContentType parameterization

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

Method

Description

ForWebsite

Configures the query to retrieve webpages from a specified website channel. Specify the following parameters:

  • websiteChannelName – code name of the website channel from which the pages are retrieved.
  • pathMatch – a parameter of type PathMatch used to limit the retrieved pages only to a certain section of the website’s content tree.
  • includeUrlPath – indicates if the URL path should be included in the retrieved data.
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 more information.

WithLinkedItems

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

WithLinkedItems

var builder = new ContentItemQueryBuilder();

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

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


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.


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;
}

LinkedFrom

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

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 and the field 'StaffField'
    subqueryParameters.LinkedFrom("project.store", "StaffField", storesCollection);
});

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

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:

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 already implement IContentItemIdentifier via the SystemFields property. The following approach applies for custom model classes.

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; }
}

Linking

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

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);
});

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:

Linking 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.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.

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; }
}

> Back to the top

ForContentTypes parameterization

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

Method

Description

OfContentType

Selects items with the specified content types.

Retrieve based on content type

var builder = new ContentItemQueryBuilder();

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

OfReusableSchema

Selects items with the specified reusable field schema.

Retrieve based on reusable field schema

var builder = new ContentItemQueryBuilder();

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

ForWebsite

Provides multiple overloads that can:

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

var builder = new ContentItemQueryBuilder();

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

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

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

    // Retrieves all web pages under the 'Acme' channel and 'Articles' page path
    parameters.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.

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 includes content type-specific fields to the result.

WithContentTypeFields example

var builder = new ContentItemQueryBuilder();

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

WithLinkedItems

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

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);
});

LinkedFrom

Retrieves content items of a specific type linked from the specified field. Enables loading data on-demand (lazily). The behavior is identical to ForContentType.LinkedFrom, with the only difference being that you cannot chain multiple calls within a single subquery.

Linking

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

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 its field. 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.
ForContentTypes.Linking usage

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

Where conditions

Where parameterization can be added to ForContentTypes queries using Parameters.

Adding Where conditions

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

> Back to the top

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.

To see how the configuration affects the data retrieval, check out the examples at Retrieve page content.

> Back to the top