Wednesday, 18 May 2016

How to Retrieve Linked Entity Data using Query Expression in MS CRM SDK

Most often you need to retrieve data from primary and related entity. This data can be retrieved using CRM SDK either with FetchXML or Query Expression.  In this blog, QueryExpression is used to retrieve primary and related entity data with a single database retrieve.


Parent Entity:-


 var query = new QueryExpression("account");


 var columnNames = new[] {"fullname", "accountid" };


 query.ColumnSet = new ColumnSet(columnNames);


 query.Criteria.AddCondition("accountid", ConditionOperator.Equal, new Guid(<<ENTER GUID HERE>>));

Linked Entity:-

var colsAccount = new[] { "firstname", "lastname" };


LinkEntity linkEntityAccount = new LinkEntity()
{


          LinkFromEntityName = "account",


          LinkFromAttributeName ="primarycontact",


          LinkToEntityName = "contact",


    LinkToAttributeName = "contactid",


          JoinOperator = JoinOperator.Inner,


    Columns = new ColumnSet(colsAccount),


    EntityAlias = "Contacts"


   };


 query.LinkEntities.Add(linkEntityAccount);
    
/* Execute Query using RetrieveMultiple
The RetrieveMultipleRequest is for returning multiple instances of a particular type of entity.*/

EntityCollection _results = _serviceproxy.RetrieveMultiple(query);
        if (_results != null)
             {
                foreach (var ent in _results.Entities)
               {
     // Display “First Name” along with Alias
     Console.WriteLine((ent.Attributes["Contacts.firstname"] as AliasedValue).Value);
     // Display “Last Name” along with Alias
     Console.WriteLine((ent.Attributes["Contacts.lastname"] as AliasedValue).Value);
                           
}
                        }

No comments:

Post a Comment