简体   繁体   中英

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);

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);
}

Do you want to retrieve leads that have a specific mail? Something like this can be done in that case.

private EntityCollection GetLeadsWithEmail(
  IOrganizationService service, String wantedEmailAddress)
{
  QueryExpression query = new QueryExpression();
  query.EntityName = "lead";
  // the columns you want
  query.ColumnSet = new ColumnSet() { AllColumns = true };

  query.Criteria = new FilterExpression();
  query.Criteria.FilterOperator = LogicalOperator.And;
  query.Criteria.Conditions.Add(new ConditionExpression(
    "emailaddress1", ConditionOperator.Equal, wantedEmailAddress));
  return service.RetrieveMultiple(query);
}

This will retrieve all the leads that have wantedEmailAddress in their emailaddress1 field. You can then check if there were any matches from where you called it;

EntityCollection leadCollection = GetLeadsWithEmail(
  service, "someone@example.com");
Entity entity = leadCollection[0];

You probably should first check the number of entities in the collection with leadCollection.Entities.Count and continue from there.

Here's a sample from MSDN.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM