This morning I was adding some functionality to my Dynamics Tutorials site and needed to determine if a user was a member of a specific marketing list.
No problem, I thought. I opened up the most excellent Stunnware Tools to create the query.
The only problem is that the Marketing List Member entity, listmember, does not support the RetreiveMultiple message, which means I can’t use QueryExpression to perform the query.
After digging around a while, I found that I could use QueryExpression but I would have to use the LinkEntity property to properly assemble the query. Here is what I came up with:
bool retVar = false; QueryExpression query = new QueryExpression { EntityName = EntityName.list.ToString()}; LinkEntity linkEntity1 = new LinkEntity { JoinOperator = JoinOperator.Natural, LinkFromEntityName = "list", LinkFromAttributeName = "listid", LinkToEntityName = "listmember", LinkToAttributeName = "listid", LinkCriteria = new FilterExpression() }; linkEntity1.LinkCriteria.FilterOperator = LogicalOperator.And; linkEntity1.LinkCriteria.AddCondition(new ConditionExpression { AttributeName = "listid", Operator = ConditionOperator.Equal, Values = new Object[] { marketingListId } }); linkEntity1.LinkCriteria.AddCondition(new ConditionExpression { AttributeName = "entityid", Operator = ConditionOperator.Equal, Values = new Object[] { userId } }); query.LinkEntities.Add(linkEntity1); RetrieveMultipleRequest request = new RetrieveMultipleRequest { ReturnDynamicEntities = true, Query = query }; RetrieveMultipleResponse response = (RetrieveMultipleResponse)crmService.Execute(request); retVar = (response.BusinessEntityCollection.BusinessEntities.Count > 0);
How It Works
1) We start by querying the Marketing List Entity ( list ).
2) We create a link entity that joins the Marketing List Member Entity to the Marketing List Entity.
3) The search criteria is actually specified on the linked, Marketing List Member Entity. We’re asking for a specific userId and a specific marketingListId.
4) Next we add the linked entity to the query.
5) Finally we prepare and execute the request.
Since I am only interested if the contact exists within the marketing list, I simple set a boolean variable to true or false depending if the number of records returned ( found in the BusinessEntityCollection ) is greater than zero.