Поделиться через


Sample: Retrieve with one-to-many relationship

 

Applies To: Dynamics 365 (online), Dynamics 365 (on-premises), Dynamics CRM 2016, Dynamics CRM Online

Requirements

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

Example

The following sample shows how to use the RetrieveMultiple method to return the 1:N related entities of an entity along with the primary entity. In this example, we retrieve an account and its related tasks.

Console.WriteLine("One-to-many Query using RetrieveMultiple");
    Console.WriteLine();
//Create an account and three related tasks
    Account account = new Account();
    account.Name = "SDK Test Account";
    Guid acctId = _serviceProxy.Create(account);
    Console.WriteLine("New account created.");
    Console.WriteLine();

    Task task1 = new Task();
    task1.Subject = "Test Task1";
    task1.RegardingObjectId = new EntityReference("account", acctId);
    Guid task1Id = _serviceProxy.Create(task1);

    Task task2 = new Task();
    task2.Subject = "Test Task2";
    task2.RegardingObjectId = new EntityReference("account", acctId);
    Guid task2Id = _serviceProxy.Create(task2);

    Task task3 = new Task();
    task3.Subject = "Test Task3";
    task3.RegardingObjectId = new EntityReference("account", acctId);
    Guid task3Id = _serviceProxy.Create(task2);

    Console.WriteLine("Three tasks created.");
    Console.WriteLine();

// Construct query
    // Condition where task attribute equals account id. 
    ConditionExpression condition = new ConditionExpression();
    condition.AttributeName = "regardingobjectid";
    condition.Operator = ConditionOperator.Equal;
    condition.Values.Add(acctId.ToString());

    //Create a column set.
    ColumnSet columns = new ColumnSet("subject");

    // Create query expression.
    QueryExpression query1 = new QueryExpression();
    query1.ColumnSet = columns;
    query1.EntityName = "task";
    query1.Criteria.AddCondition(condition);

    EntityCollection result1 = _serviceProxy.RetrieveMultiple(query1);

    foreach (var r in result1.Entities)
    {
        Console.WriteLine(r.Attributes["subject"]);
    };
    Console.WriteLine("-------------------------------");
    Console.WriteLine();

See Also

IOrganizationService
QueryExpression
IOrganizationService
RetrieveMultiple
Build queries with QueryExpression
Sample: Retrieve multiple with the QueryByAttribute class

Microsoft Dynamics 365

© 2016 Microsoft. All rights reserved. Copyright