Export (0) Print
Expand All

Sample: Retrieve multiple with the QueryExpression class

Applies To: Microsoft Dynamics CRM 2013, Microsoft Dynamics CRM Online


For more information about the requirements for running the sample code provided in this SDK, see Use the sample and helper code.


This sample shows how to retrieve multiple entities using the RetrieveMultiple method with QueryExpression along with their related entity columns. The code returns columns from the primary account record as well as the firstname and lastname of the primary contacts associated with the account.

static void RetrieveMultipleWithRelatedEntityColumns()
    //Create multiple accounts with primary contacts
    Entity contact = new Entity("contact");
    contact.Attributes["firstname"] = "ContactFirstName";
    contact.Attributes["lastname"] = "ContactLastName";
    Guid contactId = _orgService.Create(contact, null);

    Entity account = new Entity("account");
    account["name"] = "Test Account1";
    EntityReference primaryContactId = new EntityReference("contact", contactId);
    account["primarycontactid"] = primaryContactId;

    Guid accountId1 = _orgService.Create(account, null);
    account["name"] = "Test Account2";
    Guid accountId2 = _orgService.Create(account, null);
    account["name"] = "Test Account3";
    Guid accountId3 = _orgService.Create(account, null);

    //Create a query expression specifying the link entity alias and the columns of the link entity that you want to return
    QueryExpression qe = new QueryExpression();
    qe.EntityName = "account";
    qe.ColumnSet = new ColumnSet();

    qe.LinkEntities.Add(new LinkEntity("account", "contact", "primarycontactid", "contactid", JoinOperator.Inner));
    qe.LinkEntities[0].Columns.AddColumns("firstname", "lastname");
    qe.LinkEntities[0].EntityAlias = "primarycontact";

    EntityCollection ec = _orgService.RetrieveMultiple(qe);

    Console.WriteLine("Retrieved {0} entities", ec.Entities.Count);
    foreach (Entity act in ec.Entities)
       Console.WriteLine("account name:" + act["name"]);
       Console.WriteLine("primary contact first name:" + act["primarycontact.firstname"]);
       Console.WriteLine("primary contact last name:" + act["primarycontact.lastname"]);

See Also

Microsoft Dynamics CRM 2013 and Microsoft Dynamics CRM Online
Send comments about this topic to Microsoft.
© 2014 Microsoft Corporation. All rights reserved.
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
© 2014 Microsoft