Jaa


RetrieveRequest Class

Definition

Contains the data that is needed to retrieve a record.

public ref class RetrieveRequest sealed : Microsoft::Xrm::Sdk::OrganizationRequest
[System.Runtime.Serialization.DataContract(Namespace="http://schemas.microsoft.com/xrm/2011/Contracts")]
public sealed class RetrieveRequest : Microsoft.Xrm.Sdk.OrganizationRequest
[<System.Runtime.Serialization.DataContract(Namespace="http://schemas.microsoft.com/xrm/2011/Contracts")>]
type RetrieveRequest = class
    inherit OrganizationRequest
Public NotInheritable Class RetrieveRequest
Inherits OrganizationRequest
Inheritance
RetrieveRequest
Attributes

Examples

The following examples shows how to use this message. For this sample to work correctly, you must be connected to the server to get an IOrganizationService interface instance.

This SimpleRetrieveExample method focuses on processing the results returned when retrieving just the record.

Because null values are not returned with the record, you need to check whether the value exists using the Entity.Contains method or use the Entity.GetAttributeValue method to access the values.

Formatted values are available in the Entity.FormattedValues collection for EntityReferenceDateTimeMoney and OptionSetValue columns. Learn more about accessing formatted values

/// <summary>
/// Retrieves an account record and accesses the results
/// </summary>
/// <param name="service">Authenticated IOrganizationService instance</param>
static void SimpleRetrieveExample(IOrganizationService service)
{

    string tableLogicalName = "account";
    // Replace this ID with an account.accountid from your environment
    string id = "78914942-34cb-ed11-b596-0022481d68cd";
    Guid guid = new(id);

    RetrieveRequest request = new()
    {
        ColumnSet = new ColumnSet(
          "accountcategorycode",
          "address1_latitude",
          "address1_longitude",
          "creditonhold",
          "lastonholdtime",
          "numberofemployees",
          "primarycontactid",
          "revenue",
          "name"
          ),
        Target = new EntityReference(tableLogicalName, guid)
    };

    var response = (RetrieveResponse)service.Execute(request);

    Entity account = response.Entity;

    // Null values are not returned, so you must 
    // first check if they are in the collection using Entity.Contains
    string formattedaccountcategorycode = account.Contains("accountcategorycode") ?
        // Access formatted values for choice columns
        account.FormattedValues["accountcategorycode"] :
        string.Empty;

    string formattedlastonholdtime = account.Contains("lastonholdtime") ?
        // Access formatted values for DateTime columns
        account.FormattedValues["lastonholdtime"] :
        string.Empty;

    string primarycontactName = account.Contains("primarycontactid") ?
        // Access formatted values for Lookup columns
        account.FormattedValues["primarycontactid"] :
        string.Empty;

    Guid? primarycontactId = account.Contains("primarycontactid") ?
        // Access the GUID ID value from a lookup column
        account.GetAttributeValue<EntityReference>("primarycontactid").Id :
        null;

    string formattedRevenue = account.Contains("revenue") ?
        // Access formatted values for Money columns
        account.FormattedValues["revenue"] :
        string.Empty;

    decimal? revenue = account.Contains("revenue") ?
        // Access the decimal Value from a Money column
        account.GetAttributeValue<Money>("revenue").Value :
        null;

    Console.WriteLine($"ID: {account.Id}");

    // Use Entity.GetAttributeValue to access the value.
    // If a value was not returned, the default value of the type is returned
    Console.WriteLine($"name: {account.GetAttributeValue<string>("name")}");
    Console.WriteLine($"accountcategorycode: {formattedaccountcategorycode}");
    Console.WriteLine($"address1_latitude: {account.GetAttributeValue<double>("address1_latitude")}");
    Console.WriteLine($"address1_longitude: {account.GetAttributeValue<double>("address1_longitude")}");
    Console.WriteLine($"creditonhold: {account.GetAttributeValue<bool>("creditonhold")}");
    Console.WriteLine($"lastonholdtime: {formattedlastonholdtime}");
    Console.WriteLine($"numberofemployees: {account.GetAttributeValue<int>("numberofemployees")}");
    Console.WriteLine($"primarycontactName: {primarycontactName}");
    Console.WriteLine($"primarycontactid: {primarycontactId}");
    Console.WriteLine($"formattedRevenue: {formattedRevenue}");
    Console.WriteLine($"revenue: {revenue}");
}

Output

If the record has data for all the requested columns, the output should look something like this:

ID: 78914942-34cb-ed11-b596-0022481d68cd
name: Litware, Inc. (sample)
accountcategorycode: Standard
address1_latitude: 47.77777
address1_longitude: -122.13684
creditonhold: True
lastonholdtime: 9/13/2023 11:13 PM
numberofemployees: 2000
primarycontactName: Susanna Stubberod (sample)
primarycontactid: 70bf4d48-34cb-ed11-b596-0022481d68cd
formattedRevenue: $2,000,000.00
revenue: 2000000.0000

When the record doesn't have data for all the requested columns, the output should look something like this:

ID: 560bb46c-2d71-ee11-9ae7-000d3a9933c9
name: Account record without data
accountcategorycode:
address1_latitude: 0
address1_longitude: 0
creditonhold: False
lastonholdtime:
numberofemployees: 0
primarycontactName:
primarycontactid:
formattedRevenue:
revenue:

The following RetrieveWithRelatedRecords method focuses on defining queries to retrieve related records using the RetrieveRequest.RelatedEntitiesQuery property. This method uses a RelationshipQueryCollection to include queries for related task and contact records.

In the response, you access the data using the Entity.RelatedEntities property using a Relationship as the indexer value.

/// <summary>
/// Demonstrates retrieving related records with Retrieve
/// </summary>
/// <param name="service">Authenticated IOrganizationService instance</param>
static void RetrieveWithRelatedRecords(IOrganizationService service) {

    string tableLogicalName = "account";
    // Replace this ID with an account.accountid from your environment
    string id = "78914942-34cb-ed11-b596-0022481d68cd";
    Guid guid = new(id);

    // Initialize queries for related records
    RelationshipQueryCollection relationshipQueryCollection = new();

    // Add query for related tasks
    QueryExpression relatedTasks = new("task")
    {
        ColumnSet = new ColumnSet("subject", "description")
    };
    Relationship taskRelationship = new("Account_Tasks");

    relationshipQueryCollection.Add(taskRelationship, relatedTasks);


    // Add query for related Primary Contact
    QueryExpression relatedContacts = new("contact")
    {
        ColumnSet = new ColumnSet("fullname", "emailaddress1")
    };
    Relationship contactRelationship = new("account_primary_contact");

    relationshipQueryCollection.Add(contactRelationship, relatedContacts);

    RetrieveRequest request = new()
    {
        ColumnSet = new ColumnSet(
        "name"
        ),
        Target = new EntityReference(tableLogicalName, guid),
        RelatedEntitiesQuery = relationshipQueryCollection
    };

    var response = (RetrieveResponse)service.Execute(request);

    Entity account = response.Entity;

    Console.WriteLine($"ID: {account.Id}");
    Console.WriteLine($"name: {account.GetAttributeValue<string>("name")}");

    Entity? primaryContact = account
        .RelatedEntities[new Relationship("account_primary_contact")]
        .Entities
        .FirstOrDefault();

    if (primaryContact != null)
    {
        Console.WriteLine("\nPrimary Contact:");
        Console.WriteLine($"\tprimary contact ID: {primaryContact.Id}");
        Console.WriteLine($"\tprimary contact name: {primaryContact.GetAttributeValue<string>("fullname")}");
        Console.WriteLine($"\tprimary contact email: {primaryContact.GetAttributeValue<string>("emailaddress1")}");
    }

    List<Entity> tasks = account
        .RelatedEntities[new Relationship("Account_Tasks")]
        .Entities
        .ToList();

    if(tasks.Count > 0)
    {
        Console.WriteLine("\nTasks:");
        foreach (Entity task in tasks)
        {
            Console.WriteLine();
            Console.WriteLine($"\tID: {task.Id}");
            Console.WriteLine($"\ttask subject: {task.GetAttributeValue<string>("subject")}");
            Console.WriteLine($"\ttask description: {task.GetAttributeValue<string>("description")}");
        }
    }
}

Output:

If the account record you selected has related contact and task records with the specified relationships, the output will look something like this:

ID: 78914942-34cb-ed11-b596-0022481d68cd
name: Litware, Inc. (sample)

Primary Contact:
        primary contact ID: 70bf4d48-34cb-ed11-b596-0022481d68cd
        primary contact name: Susanna Stubberod (sample)
        primary contact email: someone_b@example.com

Tasks:

        ID: be9f6557-e2cc-ed11-b597-000d3a993550
        task subject: Task 1 for Litware
        task description: Description for Task 1 for Litware

        ID: 605dbd65-e2cc-ed11-b597-000d3a993550
        task subject: Task 2 for Litware
        task description: Description for Task 2 for Litware

        ID: a718856c-e2cc-ed11-b597-000d3a993550
        task subject: Task 3 for Litware
        task description: Description for Task 3 for Litware

If there are no related records, the output will look something like this:

ID: 560bb46c-2d71-ee11-9ae7-000d3a9933c9
name: Account with no related records

Remarks

Learn to retrieve a table row using the SDK for .NET

Usage

Pass an instance of this class to the Execute(OrganizationRequest) method, which returns an instance of the RetrieveResponse class.

Privileges and Access Rights

To perform this action, the caller must have read privileges for the table and read access rights on the specified records in the Target property.

Notes for Callers

The returned record contains the values for the properties that are specified in the ColumnSet property for which the calling user has access rights. No other property values are returned. For more information about column security, see Column-level security to control access.

Supported Tables

See Message support for tables for an example query you can use to get the list of tables you can use with the Retrieve message.

Constructors

RetrieveRequest()

Initializes a new instance of the RetrieveRequest class.

Properties

ColumnSet

Gets or sets the collection of columns for which non-null values are returned from a query. Required.

ExtensionData

Gets or sets the structure that contains extra data. Optional.

(Inherited from OrganizationRequest)
Item[String]

Gets or sets the indexer for the Parameters collection.

(Inherited from OrganizationRequest)
Parameters

Gets or sets the collection of parameters for the request. Required, but is supplied by derived classes.

(Inherited from OrganizationRequest)
RelatedEntitiesQuery

Gets or sets the query that describes the related records to be retrieved. Optional.

RequestId

Gets or sets the ID of the request. Optional.

(Inherited from OrganizationRequest)
RequestName

Gets or sets the name of the request. Required, but is supplied by derived classes.

(Inherited from OrganizationRequest)
ReturnNotifications

For internal use only.

Target

Gets or sets the target, which is the record to be retrieved. Required.

Applies to

See also