Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I search for lead or account using Dynamics CRM SDK?

Can someone please provide a sample code for retrieving leads by email in CRM SDK? Is there any built in function that works like this?

Guid leadID = someLeadManager.GetByEmail(email);
like image 730
David Smithers Avatar asked Dec 11 '22 17:12

David Smithers


1 Answers

Assuming that you've obtained the service, you can execute the following query.

private Guid GetGuidByEmail(String email)
{
  QueryExpression query = new QueryExpression
  {
    EntityName = "lead",
    ColumnSet = new ColumnSet("emailaddress1"),
    Criteria = new FilterExpression
    {
      Filters =
      {
        new FilterExpression
        {
          Conditions =
          {
            new ConditionExpression(
              "emailaddress1", ConditionOperator.Equals, email)
          }
        }
      }
    }
  };

  Entity entity = service.RetrieveMultiple(query).Entities.FirstOrDefault();
  if(entity != null)
    return entity.Id;
  return Guid.Empty;
}

Now, if you need filtration for a match of part of the email, the query gets shorter, and instead, you can do the selection using LINQ like this.

private IEnumerable<Guid> GetGuidsByEmail(String email)
{
  QueryExpression query = new QueryExpression
  {
    EntityName = "lead",
    ColumnSet = new ColumnSet("emailaddress1")
  };
  IEnumerable<Entity> entities = service.RetrieveMultiple(query).Entities;

  return entities
    .Where(element => element.Contains("emailaddress1"))
      .Where(element => Regex.IsMatch(element["emailaddress1"], email))
        .Select(element => element.Id);
}
like image 116
Konrad Viltersten Avatar answered Dec 14 '22 05:12

Konrad Viltersten