IOrganizationService.Retrieve Method

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

Retrieves a record.

Namespace: Microsoft.Xrm.Sdk
Assembly: Microsoft.Xrm.Sdk (in Microsoft.Xrm.Sdk.dll)

Syntax

'Declaration
<FaultContractAttribute(GetType(OrganizationServiceFault))> _
<OperationContractAttribute> _
Function Retrieve ( _
    entityName As String, _
    id As Guid, _
    columnSet As ColumnSet _
) As Entity
[FaultContractAttribute(typeof(OrganizationServiceFault))] 
[OperationContractAttribute] 
Entity Retrieve (
    string entityName,
    Guid id,
    ColumnSet columnSet
)

Parameters

  • entityName
    Type: String. The logical name of the entity that is specified in the entityId parameter.
  • id
    Type: Guid. The ID of the record that you want to retrieve.
  • columnSet
    Type: ColumnSet. A query that specifies the set of columns, or attributes, to retrieve.

Return Value

Type: Entity
The requested entity.

Example

The following example shows how to use the Retrieve method to retrieve an account record (early bound). For this sample to work correctly, you must be connected to the server to instantiate an IOrganizationService interface. You can find the complete sample in the sample code package in the folder SampleCode\CS\GeneralProgramming\EarlyBound\CRUDOperations.cs.

// Connect to the Organization service. 
// The using statement assures that the service proxy will be properly disposed.
using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
{
    // This statement is required to enable early-bound type support.
    _serviceProxy.EnableProxyTypes();

    CreateRequiredRecords();

    // Instantiate an account object.
    // See the Entity Metadata topic in the SDK documentation to determine 
    // which attributes must be set for each entity.
    Account account = new Account { Name = "Fourth Coffee" };

    // Create an account record named Fourth Coffee.
    _accountId = _serviceProxy.Create(account);
    Console.Write("{0} {1} created, ", account.LogicalName, account.Name);

    // Retrieve the account containing several of its attributes.
    ColumnSet cols = new ColumnSet(
        new String[] { "name", "address1_postalcode", "lastusedincampaign", "versionnumber" });

    Account retrievedAccount = (Account)_serviceProxy.Retrieve("account", _accountId, cols);
    Console.Write("retrieved ");

    // Retrieve version number of the account. Shows BigInt attribute usage.
    long? versionNumber = retrievedAccount.VersionNumber;

    if (versionNumber != null)
        Console.WriteLine("version # {0}, ", versionNumber);

    // Update the postal code attribute.
    retrievedAccount.Address1_PostalCode = "98052";

    // The address 2 postal code was set accidentally, so set it to null.
    retrievedAccount.Address2_PostalCode = null;

    // Shows usage of option set (picklist) enumerations defined in OptionSets.cs.
    retrievedAccount.Address1_AddressTypeCode = new OptionSetValue((int)AccountAddress1_AddressTypeCode.Primary);
    retrievedAccount.Address1_ShippingMethodCode = new OptionSetValue((int)AccountAddress1_ShippingMethodCode.DHL);
    retrievedAccount.IndustryCode = new OptionSetValue((int)AccountIndustryCode.AgricultureandNonpetrolNaturalResourceExtraction);

    // Shows use of a Money value.
    retrievedAccount.Revenue = new Money(5000000);

    // Shows use of a Boolean value.
    retrievedAccount.CreditOnHold = false;

    // Shows use of EntityReference.
    retrievedAccount.ParentAccountId = new EntityReference(Account.EntityLogicalName, _parentAccountId);

    // Shows use of Memo attribute.
    retrievedAccount.Description = "Account for Fourth Coffee.";

    // Update the account record.
    _serviceProxy.Update(retrievedAccount);
    Console.WriteLine("and updated.");                    

    DeleteRequiredRecords(promptforDelete);
}

The following example shows how to use the Retrieve method to retrieve an account record (late bound). For this sample to work correctly, you must be connected to the server to instantiate an IOrganizationService interface. You can find the complete sample in the sample code package in the folder SampleCode\CS\GeneralProgramming\LateBound\CRUDOperationsDE.cs.

// Instaniate an account object.
Entity account = new Entity("account");

// Set the required attributes. For account, only the name is required. 
// See the Entity Metadata topic in the SDK documentatio to determine 
// which attributes must be set for each entity.
account["name"] = "Fourth Coffee";

// Create an account record named Fourth Coffee.
_accountId = _service.Create(account);

Console.Write("{0} {1} created, ", account.LogicalName, account.Attributes["name"]);

// Create a column set to define which attributes should be retrieved.
ColumnSet attributes = new ColumnSet(new string[] { "name", "ownerid" });

// Retrieve the account and its name and ownerid attributes.
account = _service.Retrieve(account.LogicalName, _accountId, attributes);
Console.Write("retrieved, ");

// Update the postal code attribute.
account["address1_postalcode"] = "98052";

// The address 2 postal code was set accidentally, so set it to null.
account["address2_postalcode"] = null;

// Shows use of Money.
account["revenue"] = new Money(5000000);

// Shows use of boolean.
account["creditonhold"] = false;

// Update the account.
_service.Update(account);
Console.WriteLine("and updated.");

// Delete the account.
bool deleteRecords = true;

if (promptForDelete)
{
    Console.WriteLine("\nDo you want these entity records deleted? (y/n) [y]: ");
    String answer = Console.ReadLine();

    deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y") || answer == String.Empty);
}

if (deleteRecords)
{
    _service.Delete("account", _accountId);

    Console.WriteLine("Entity record(s) have been deleted.");
}

Remarks

Message Availability

This message works regardless whether the caller is connected to the server or offline.

Not all entity types support this message offline. See Supported Entities later in this topic.

Privileges and Access Rights

To perform this action, the caller must have privileges on the entity that is specified in the entityName parameter and access rights on the record that is specified in the id parameter. For a list of the required privileges, see Retrieve Privileges.

Notes for Callers

The returned record contains values for the specified properties in the columnSet parameter for which the calling user has access rights. Any other property values are not returned. For more information, see The Security Model of Microsoft Dynamics CRM.

Pass null for the columnSet parameter to retrieve only the primary key. If the columnSet includes attributes where IsValidForRead is false, they are ignored. You can find this information in the metadata for your organization. See the preceding metadata browser information.

To retrieve a record and its related records in a single transaction, use the RetrieveRequest class.

You can use this method to retrieve any record of an entity that supports the Retrieve message, including custom entities.

For more information about the exceptions that can be thrown when this method is called, see Handle Exceptions in Your Code.

Supported Entities

The following table shows the default entities that support this message. For the listed entities of this message, the Availability column shows Server if the caller must be connected to the server and shows Both if the caller can be either connected to, or disconnected from, the server.

Entity Availability

account

Both

activitymimeattachment

Both

activitypointer

Both

annotation

Both

annualfiscalcalendar

Both

appointment

Both

asyncoperation

Both

attributemap

Server

audit

Server

bulkdeletefailure

Both

bulkdeleteoperation

Both

bulkoperation

Both

bulkoperationlog

Both

businessunit

Both

businessunitnewsarticle

Both

calendar

Both

campaign

Both

campaignactivity

Both

campaignresponse

Both

columnmapping

Both

competitor

Both

connection

Both

connectionrole

Both

connectionroleobjecttypecode

Both

constraintbasedgroup

Both

contact

Both

contract

Both

contractdetail

Both

contracttemplate

Both

customeraddress

Both

customeropportunityrole

Both

customerrelationship

Both

dependency

Server

discount

Both

discounttype

Both

displaystring

Both

duplicaterecord

Server

duplicaterule

Server

duplicaterulecondition

Server

email

Both

entitymap

Server

equipment

Both

fax

Both

fieldpermission

Server

fieldsecurityprofile

Server

fixedmonthlyfiscalcalendar

Both

goal

Both

goalrollupquery

Both

import

Both

importentitymapping

Both

importfile

Both

importjob

Both

importlog

Both

importmap

Both

incident

Both

incidentresolution

Both

invaliddependency

Server

invoice

Both

invoicedetail

Both

isvconfig

Server

kbarticle

Both

kbarticlecomment

Both

kbarticletemplate

Both

lead

Both

leadaddress

Both

letter

Both

list

Both

lookupmapping

Both

mailmergetemplate

Both

metric

Both

monthlyfiscalcalendar

Both

msdyn_postalbum

Server

msdyn_postconfig

Server

msdyn_postruleconfig

Server

opportunity

Both

opportunityclose

Both

opportunityproduct

Both

orderclose

Both

organization

Both

organizationui

Both

ownermapping

Both

phonecall

Both

picklistmapping

Both

pluginassembly

Both

plugintype

Both

plugintypestatistic

Server

post

Server

postcomment

Server

postfollow

Server

postlike

Server

pricelevel

Both

principalobjectattributeaccess

Both

privilege

Both

processsession

Both

product

Both

productpricelevel

Both

publisher

Both

publisheraddress

Server

quarterlyfiscalcalendar

Both

queue

Both

queueitem

Both

quote

Both

quoteclose

Both

quotedetail

Both

recurrencerule

Both

recurringappointmentmaster

Both

relationshiprole

Both

relationshiprolemap

Both

report

Both

reportcategory

Both

reportentity

Both

reportlink

Both

reportvisibility

Both

resource

Both

resourcegroup

Both

resourcespec

Both

role

Both

rollupfield

Both

salesliterature

Both

salesliteratureitem

Both

salesorder

Both

salesorderdetail

Both

savedquery

Both

savedqueryvisualization

Both

sdkmessage

Both

sdkmessagefilter

Both

sdkmessagepair

Both

sdkmessageprocessingstep

Both

sdkmessageprocessingstepimage

Both

sdkmessageprocessingstepsecureconfig

Server

sdkmessagerequest

Both

sdkmessagerequestfield

Both

sdkmessageresponse

Both

sdkmessageresponsefield

Both

semiannualfiscalcalendar

Both

service

Both

serviceappointment

Both

serviceendpoint

Server

sharepointdocumentlocation

Server

sharepointsite

Server

site

Both

sitemap

Both

solution

Both

solutioncomponent

Both

subject

Both

systemform

Both

systemuser

Both

task

Both

team

Both

template

Both

territory

Both

timezonedefinition

Both

timezonelocalizedname

Both

timezonerule

Both

transactioncurrency

Both

transformationmapping

Both

transformationparametermapping

Both

uom

Both

uomschedule

Both

userentityinstancedata

Both

userentityuisettings

Both

userform

Both

userquery

Both

userqueryvisualization

Both

usersettings

Both

webresource

Both

workflow

Server

workflowdependency

Server

workflowlog

Server

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Platforms

Development Platforms

Windows Server 2008, Windows Server 2012, Windows 7 (All Versions), Windows 8 (All Versions)

Target Platforms

Windows Server 2008, ,Windows Server 2012, ,Windows 7 (All Versions),

Change History

See Also

Reference

IOrganizationService Interface
IOrganizationService Members
Microsoft.Xrm.Sdk Namespace
RetrieveResponse
RetrieveRequest
Retrieve

Other Resources

Handle Exceptions in Your Code
Troubleshooting and Error Handling

Send comments about this topic to Microsoft.
© 2013 Microsoft Corporation. All rights reserved.