Introduction
When we setup system N:N relationship between two entities an intersect entity is created internally, which is not accessible directly. Let’s say we have N:N relationship between case and workorder entity.
And if you will try to see attributes of this entity, you will find following attributes
So in case we want to query this entity, we need to query it based on the the related entities. If you are looking for the sample code to query intersect entity and get it’s attribute this post will help you.
Requirement
Query above intersect entity and check if there is any work order associated to case, if yes we want to get workorderid.
Solution
As said we can’t query intersect entity directly but we can query it using case or work order, in our case we will be query it with case entity. We are going to use QueryExpression class here and will be using it’s AddLink method to get data from intersect entity. We can use following code
//Create Query Expression. QueryExpression query = new QueryExpression() { EntityName = "incident", ColumnSet = new ColumnSet("title"), LinkEntities = { new LinkEntity { LinkToEntityName = "him_incident_msdyn_workorder", //name of the intersect entity LinkFromAttributeName="incidentid", LinkToAttributeName = "incidentid", Columns=new ColumnSet(new string[]{"msdyn_workorderid" }), //workorder id in interset entity EntityAlias="intersect", //add alias name to refer attribute easily LinkCriteria = new FilterExpression { FilterOperator = LogicalOperator.And, Conditions = { new ConditionExpression { AttributeName = "incidentid", Operator = ConditionOperator.Equal, Values = { caseid } } } } } } }; // Obtain results from the query expression. EntityCollection results = service.RetrieveMultiple(query);
Now if get workorderid we need to use AliasedValue class here, for example to get first workorderid, we need to use following code
Guid workorderid =new Guid(result.Entities[0].GetAttributeValue<AliasedValue>("intersect.msdyn_workorderid").Value.ToString());
Pingback: Query intersect entity and it’s attribute- Sample Code - Microsoft Dynamics CRM Community