Get contact based on Business Unit name
Get contact based on name and it’s BU- Sample Code
Category: Dynamics 365,Dynamics 365 CE Online,Get contact based on Business Unit name,Get contact business unit using query expression,MS CRM 2015,Ms CRM 2016,Query Expression,Using link entity with query expression Author: HIMBAP Date: 11 months ago Comments: 0

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.ColumnSet.AddColumns("fullname");
            query.Criteria.AddCondition("fullname", ConditionOperator.Equal, contact);
			
			//add link entity condition
            var linkEntity = query.AddLink("businessunit", "owningbusinessunit", "businessunitid");
            linkEntity.EntityAlias = "BU";
            linkEntity.Columns.AddColumns("businessunitid");
            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 !!

Source: Mahendra Pal