To render dynamic contents, using broker query to get related components tcmuri. Now using these component tcm-uri's need to get the Component Template Id. Since we need both Component Id and Component Template Id to get the Content and Metadata of the component. Below is the code currently used, but not sure if this is a correct approach. Please advice the best way to achieve this and also welcome to advice on this whole approach of getting the dynamic content. Thanks in Advance.
public void PopulateDynamicList(DynamicList dynamicList, Localization localization)
{
using (new Tracer(dynamicList, localization))
{
SimpleBrokerQuery simpleBrokerQuery = dynamicList.GetQuery(localization) as SimpleBrokerQuery;
if (simpleBrokerQuery == null)
{
throw new DxaException($"Unexpected result from {dynamicList.GetType().Name}.GetQuery: {dynamicList.GetQuery(localization)}");
}
BrokerQuery brokerQuery = new BrokerQuery(simpleBrokerQuery);
string[] componentUris = brokerQuery.ExecuteQuery().ToArray();
if (componentUris.Length > 0)
{
Type resultType = dynamicList.ResultType;
ComponentPresentationFactory cpf = new ComponentPresentationFactory(localization.GetCmUri());
IList cpList = null;
string componentTemplateId = string.Empty;
foreach (var compUri in componentUris)
{
cpList = cpf.FindAllComponentPresentations(compUri);
}
if (cpList.Count == 1)
{
ComponentPresentation compPresentation = (ComponentPresentation)cpList[0];
componentTemplateId = localization.GetCmUri(compPresentation.ComponentTemplateId.ToString());
}
dynamicList.QueryResults = componentUris
.Select(c => ModelBuilderPipeline.CreateEntityModel(CreateEntityModelData(cpf.GetComponentPresentation(c, componentTemplateId), localization), resultType, localization))
.ToList();
}
dynamicList.HasMore = brokerQuery.HasMore;
}
}