Divakar Ragupathy
Divakar Ragupathy

Reputation: 211

Retrieve contact id using email id in MS Dynamics CRM

I want to retrieve the contact id eg (3a361fd6-e276-e911-9714-00155d96a17d) using the contact's email id in MS Dynamics CRM using C#

Can someone please help me? Below is my code

Uri UrlCrm = new Uri(CRMUrl);
String UserLogin = Domain + "\\" + Username;
String password = Password;
ClientCredentials credentials = new ClientCredentials();

credentials.Windows.ClientCredential.UserName = UserLogin;
credentials.Windows.ClientCredential.Password = password;
OrganizationServiceProxy serverProxy = new OrganizationServiceProxy(UrlCrm, null, credentials, null);

IOrganizationService service;
service = (IOrganizationService)serverProxy;

QueryExpression query = new QueryExpression("contact");
    string[] cols = { "contactid", "emailaddress1" };
    query.Criteria = new FilterExpression();
    query.Criteria.AddCondition("emailaddress1", ConditionOperator.Equal, "[email protected]");
    query.ColumnSet = new ColumnSet(cols);
    var contact = service.RetrieveMultiple(query);
    //Entity contact = new Entity("contact");
    Guid contactId = (Guid)contact.Attributes["contactid"];

GuidKey = contactId.ToString();

I am getting the following error :

Description: Compiler error at line 20: 'Microsoft.Xrm.Sdk.EntityCollection' does not contain a definition for 'Attributes' and no extension method 'Attributes' accepting a first argument of type 'Microsoft.Xrm.Sdk.EntityCollection' could be found (are you missing a using directive or an assembly reference?)

Upvotes: 1

Views: 1404

Answers (1)

AnkUser
AnkUser

Reputation: 5531

Here is the error for below code line

Guid contactId = (Guid)contact.Attributes["contactid"];

Reason: You are retrieving multiple i.e it is entity-collection. so you should iterate. Below I have given you first contact Id but you can loop through and get all ContactId's

Correct code:

if(contact.Entities.Count>0){
 Guid contactId = contact.Entities[0].Id;
}

Now if you need all the conatcId's here is one more code snippet

foreach (Entity con in contact.Entities)
                {
                    Console.WriteLine("Contact ID is: " + con.ID);

            }

Upvotes: 3

Related Questions