Get contact based on name and it’s BU- Sample Code

If you got requirement to get contact record based on it’s full name and it’s business unit name, this sample code will help you. Sharing following sample code to get contact using Query Expression.

public Entity GetContactByFullNameandBUName(string contact,string businessunit)
            Entity contactEntity = null;

            // setup query expression to query contact for fullname and BU
            var query = new QueryExpression("contact");
            query.Criteria.AddCondition("fullname", ConditionOperator.Equal, contact);
			//add link entity condition
            var linkEntity = query.AddLink("businessunit", "owningbusinessunit", "businessunitid");
            linkEntity.EntityAlias = "BU";
            linkEntity.LinkCriteria.AddCondition("name", ConditionOperator.Equal, businessunit);
			//execute query
            EntityCollection results = organizationService.RetrieveMultiple(query);

           if (results.Entities.Count>0)
                contactEntity = results.Entities.FirstOrDefault();

            return contactEntity;

Hope it will help someone !!

Leave a Reply

Your email address will not be published. Required fields are marked *