Martin Wedvich
Martin Wedvich

Reputation: 2266

Dynamics CRM 2011 - Getting set of N:1 related entities with QueryExpression

I'm working on a custom web service for a CRM 2011 deployment, and I'm now making an overview which relates to some of our entities. We have a custom product entity with details such as the product name and category, and we have an agreement entity, which links the product to the customer and contains product details specific to that customer. agreement and product have an N:1 relationship.

I'm now making an overview page that will be displayed on the customer page in CRM, which should display all agreements on that customer. For this display, I also need to retrieve some information about the products these agreements link to, which will be used to group the agreements on the overview page. I've been unable to find any relevant/specific examples on this, and I'm stuck trying to find a feasible way of querying for the data I need.

The way I imagine it, I would like to use two queries to get the required data. First, a query that gets all the agreements on the customer. Then pass this list to a second query, which returns all the products that intersect the first list. Is this possible using a QueryExpression, or do I need to loop over the agreement list and run a separate query for each individual association? I'd prefer to avoid FetchXML if possible.

Upvotes: 2

Views: 1845

Answers (3)

Martin Wedvich
Martin Wedvich

Reputation: 2266

I looked at LinkEntity, but I eventually achieved what I wanted to do with ConditionOperator.In on the second query, like this:

query.Criteria.AddCondition(
    new ConditionExpression(
        "myprefix_productid",
        ConditionOperator.In,
        agreementList )
);

Where agreementList is an array of Guids. I tried this before posting the question as well, but without wrapping the parameters in new ConditionExpression(), which didn't work. Presumably this was because the implicit way invoked the wrong overload for the AddCondition function.

Useful links in the other answers though, I'll look into them as well!

Upvotes: 0

Konrad Viltersten
Konrad Viltersten

Reputation: 39268

Adding to Daryls answer, you can see this post for an example on how to link entities. MSDN is confusing on the subject (at least to me).

I'm proposing a nice structure of query expression there, while Daryl presents a more compact equivalent. (Mine is of course better. :D )

Upvotes: 1

Daryl
Daryl

Reputation: 18895

If I understand your question right, you'll just need to add a LinkEntity to your Product entity on the first query. You can also specify attributes of the Product entity to return as well, but they get returned as AliasedValues, so be aware of that.

Upvotes: 3

Related Questions