Tuesday, September 23, 2008

Retrieve Associated Many to Many Relationship Records.


In our last post we have seen "Creating Records for Many to Many Relationship in MS CRM".

Now how do you retrieve the (many to many) records ?

Its Very Easy .... :) I'm serious.... See below function........

Lets assume, we have "Hotel Reservation" and "Guest" Entity. We have many to many relationship between Guest and HotelReservation Entity.

Below function will return the list of Hotel Reservations (Guids) for the Guest.



public List GetAllAssocaitedRecords(Guid GuestGuid) 
{ 
    string strEntityRelationshipName = "Specify Relationship Name";
 
    List ObjHotelReservationGuids = new List();
 
    string fetchXml = @"<fetch mapping=""logical""> <entity name=""@HotelReservationContactRelation"">
                            <all-attributes />
                            <filter>
                                <condition attribute=""contactid"" operator=""eq"" value =""@GuestGuid"" />
                            </filter>
                            </entity>
                        </fetch>";
 
 
    fetchXml = fetchXml.Replace("@GuestGuid", GuestGuid.ToString());
    fetchXml = fetchXml.Replace("@HotelReservationContactRelation", strEntityRelationshipName );
 
    string strResult = Service.Fetch(fetchXml);
 
    XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(strResult);
    XmlNodeList nodeList = xmlDoc.SelectNodes("resultset/result");
 
    if (nodeList.Count > 0)
    {
        foreach (XmlNode xmlNode in nodeList)
        {
            ObjHotelReservationGuids.Add(new Guid(xmlNode.SelectSingleNode("neuguest_hotelreservationid").InnerText));
        }
    }
    
    return ObjHotelReservationGuids;
}
 


Happy Coding !!!!!


1 comment:

Swathy M S said...

Thank you for the code. It was very helpful :)