This documentation is archived and is not being maintained.

Finding the ID Using QueryExpression

banner art

[Applies to: Microsoft Dynamics CRM 4.0]

Find the latest SDK documentation: CRM 2015 SDK

If the program is a Windows application or other Web service, you can use the QueryExpression class from the Microsoft Dynamics CRM Web service. This class enables you to create queries that retrieve the entity instance IDs for records that meet your criteria.


The following code sample shows you how to create a query that retrieves the account IDs for accounts whose name are like "Black".

[Visual Basic .NET]
' Set up the CRM Service.
Dim token As New CrmAuthenticationToken()
token.AuthenticationType = 0
token.OrganizationName = "AdventureWorksCycle";
Dim service As New CrmService()
service.Url = ""http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials

' Create the ColumnSet to indicate the fields to be retrieved.
Dim cols As New ColumnSet()
cols.Attributes = New String() {"name", "accountid"}

' Create the ConditionExpression.
Dim condition As New ConditionExpression()

' Set the retrieval condition to be when the account's name
' is like Black.
condition.AttributeName = "name"
condition.Operator = ConditionOperator.Like
condition.Values = New String() {"%Black%"}

' Create the FilterExpression.
Dim filter As New FilterExpression()

' Set the filter's properties.
filter.FilterOperator = LogicalOperator.And
filter.Conditions = New ConditionExpression() {condition}

' Create the QueryExpression object.
Dim query As New QueryExpression()

' Set the QueryExpression properties.
EntityName = EntityName.account.ToString()
query.ColumnSet = cols
query.Criteria = filter

' Retrieve the accounts that match the condition.
Dim accounts As BusinessEntityCollection = service.RetrieveMultiple(query)

' Iterate through the collection and use the objects
' that were returned from the query.
If accounts.BusinessEntities.Length > 0 Then
    Dim a As account = accounts.BusinessEntities(0)
    Dim accountID As Guid = a.accountid.Value
   'Do more processing from here....
End If

See Also


© 2010 Microsoft Corporation. All rights reserved.