Search code examples
c#dynamics-crmdynamics-crm-2015query-expressions

Retrieve top one record from CRM using early bound


I want to retrieve top most record from my CRM entity using early bound query expression.

I have written it as:

QueryExpression opportunityProductsQuery = new QueryExpression
        {
            EntityName = PCSEPortal.oph_ophthalmicclaim.EntityLogicalName,
            ColumnSet = new ColumnSet("Name"),
            Criteria = new FilterExpression
            {
               new ConditionExpression
                        {
                            //condition
                        }
            }
        };
        return "";

But I am not sure how to write where condition and top 1 order by Desc condition here.

For where condition, I have column as Submission channel

- Logical name - oph_submissionchannel
- Schema Name  - oph_SubmissionChannel

and order by Guid or any unique id.

How to write query expression here? Or is there any other better option? I am trying to avoid FetchXML for this.


Solution

  • You have to use PagingInfo to achieve this.

    opportunityProductsQuery.PageInfo.Count = 1;
    

    Read more. This example shows how to use LinkEntity, LinkCriteria, Sort Order Descending & PageInfo to get result.

        LinkEntity le = opportunityProductsQuery.AddLink(PCSEPortal.oph_submissionchannel.EntityLogicalName, “oph_submissionchannelid”, “2ndentityname2”);
        le.Columns = new ColumnSet(“oph_submissionchannelid”);
        le.LinkCriteria.AddCondition(“oph_submissionchannelid”, ConditionOperator.Equal, Guid);   //where condition
        opportunityProductsQuery.AddOrder(“modifiedon”, OrderType.Descending);
        opportunityProductsQuery.PageInfo = new PagingInfo();
        opportunityProductsQuery.PageInfo.Count = 1;
        opportunityProductsQuery.PageInfo.PageNumber = 1;
    
        EntityCollection entitycolls = service.RetrieveMultiple(equery);