Thursday, March 14, 2013

How to Retrieve/Get N:N(Many to Many) Records Using C# && fetchXML


Problem with retrieving Many to Many records.
Solution: Using C# fetchxml to retrieve all the information. FetchXML is generated through advance find button in CRM 2011.
Advantage: This fetchXML in C# also can be use in one to many (1:N) records too.

Function And Script


#region Fetch N:N Billing Account Filter By Scheduler

string fetchxml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>" +
                                  "<entity name='vw_billingaccountcode'>" +
                                    "<attribute name='vw_billingaccountcodeid' />" +
                                    "<attribute name='vw_name' />" +
                                    "<attribute name='createdon' />" +
                                    "<order attribute='vw_name' descending='false' />" +
                                    "<link-entity name='vw_vw_scheduler_vw_billingaccountcode' from='vw_billingaccountcodeid' to='vw_billingaccountcodeid' visible='false' intersect='true'>" +
                                      "<link-entity name='vw_scheduler' from='vw_schedulerid' to='vw_schedulerid' alias='aa'>" +
                                        "<filter type='and'>" +
                                          "<condition attribute='vw_schedulerid' operator='eq' uiname='Test' uitype='vw_scheduler' value='{" + ID.ToUpper() + "}' />" +
                                        "</filter>" +
                                      "</link-entity>" +
                                    "</link-entity>" +
                                  "</entity>" +
                                "</fetch>";

EntityCollection entities = OrgService.RetrieveMultiple(new FetchExpression(fetchxml));
foreach (Entity result in entities.Entities)
{
       string BillingAccountId = result.Id.ToString(); //All the result will be show here. Looping.
}

#endregion

No comments:

Post a comment