Search code examples
c#pluginsdynamics-crmmicrosoft-dynamicsdynamics-crm-online

invalid Argument error while retrieving values from lookup field


I have account and contact Lookup fields on Lead entity. I want to get Account Name and Email Address of Contact.

I am getting Invalid Argument error.

code :

    public EntityCollection  GetDetails()
    {
        string fetchXML = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                      <entity name='lead'>
                        <attribute name='fullname' />
                        <attribute name='leadid' />      
                        <attribute name='new_contact'/>
                        <attribute name='new_account'/>
                        <order attribute='fullname' descending='false' />
                        <filter type='and'>                             
                          <condition attribute='leadqualitycode' operator='eq' value='1' />
                        </filter>                            
                      </entity>
                    </fetch>";
        EntityCollection records = service.RetrieveMultiple(new FetchExpression(fetchXML));
        return records;         
    }

    public string GetAccountDetail(EntityCollection records)
    {
        if (records.Entities.Count != 0)
        {
            accountid = records.Entities[0].GetAttributeValue<Guid>("new_account");
            tracingService.Trace("AccountId :" + accountid);
            Entity accountDetails = service.Retrieve("account", accountid, new ColumnSet("name"));
            string accountname = accountDetails.Attributes["name"].ToString();              
            tracingService.Trace("AccountName :" + accountname);
            return accountname;
        }
        return name;
    }

Solution

  • Change this line

    accountid = records.Entities[0].GetAttributeValue<Guid>("new_account");
    

    Into

    accountid = records.Entities[0].GetAttributeValue<EntityReference>("new_account").Id;
    

    Because it’s a lookup.