CRM 2011 – Retrieve Many to Many Intersect Entity Columns Using Query Expression.


The scenario for the code goes this way :

Consider the following relationship that exists between CRM entities
Class Diagram for Many to Mant

In the above diagram ClassA is an entity in CRM and ClassB
is an entity in CRM. ClassAB is

Many-to-Many relationship. The following code in CRM 2011
will retrieve the columns of the Many to Many relationship table.

QueryExpression query = new QueryExpression()
{
EntityName = "classA",
ColumnSet = new ColumnSet(true),
LinkEntities =  new ObservableCollection<LinkEntity>()
{
new LinkEntity(){
Columns = new ColumnSet(true),
LinkFromEntityName = "classA",
LinkFromAttributeName = "classAid",
LinkToEntityName = "new_classA_new_classB",
LinkToAttributeName = "classAid"
                  }
}
};
//Call Crm Service

Collection<Entity> classAB = coreCrmService.RetrieveMultiple(query);
if (classAB != null && classAB.Count > 0)
{
foreach (Entity item in classAB)
{
AliasedValue  value = (item.Attributes["new_classA_new_classB1.classAid"]  as AliasedValue);
classAB.Add((Guid)value.Value);
}
}

return classAB;

In the above code the line “Columns = new ColumnSet(true)”
inside new LinkEntity class is the trick which fetches columns of classAB which
is the intersect table. To fetch data from is stored in the attributes
collection inside classAB and can fetchedby using key value as shown in code
above.

Advertisements

2 thoughts on “CRM 2011 – Retrieve Many to Many Intersect Entity Columns Using Query Expression.

  1. Xitij Thool

    Not working since the LinkEntities property “Gets a collection of the links between multiple entity types.” and can’t set it

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s