Dynamics 365 CRM Optimized QueryExpression snippet to retrieve data from 4 Down Hierarchal entities
QueryExpression userquery = new QueryExpression("systemuser");
userquery.NoLock = true;
userquery.Distinct = true;
userquery.ColumnSet = new ColumnSet("systemuserid", "fullname");
userquery.Criteria.AddCondition("isdisabled", ConditionOperator.Equal, false);
LinkEntity elink = new LinkEntity("systemuser", "employee", "employee", "employeeid", JoinOperator.Inner);
userquery.LinkEntities.Add(elink);
LinkEntity celink = new LinkEntity("employee", "connection", "employeeid", "record2id", JoinOperator.Inner);
elink.LinkEntities.Add(celink);
LinkEntity crlink = new LinkEntity("connection", "connectionrole", "record2roleid", "connectionroleid", JoinOperator.Inner);
crlink.LinkCriteria.Conditions.Add(new ConditionExpression("category", ConditionOperator.Equal, 206490001));
if(context.MessageName == "Assign" &&
context.PrimaryEntityName == "opportunity")
crlink.LinkCriteria.Conditions.Add(new ConditionExpression("name", ConditionOperator.NotEqual, "OwnerName"));
celink.LinkEntities.Add(crlink);
celink.LinkCriteria.AddFilter(LogicalOperator.And);
LinkEntity olink = new LinkEntity("connection", "opportunity", "record1id", "opportunityid", JoinOperator.Inner);
olink.LinkCriteria.Conditions.Add(new ConditionExpression("opportunityid", ConditionOperator.Equal, _opptyid));//Pass OpportunityID Value
celink.LinkEntities.Add(olink);
var result = ImperService.RetrieveMultiple(userquery);
foreach (var a in result.Entities)
{
if(!_userlist.Contains((Guid)a.Attributes["systemuserid"]))
_userlist.Add((Guid)a.Attributes["systemuserid"]);
}