Ivan Studenikin
Ivan Studenikin

Reputation: 1463

Get entities by multiple ids in N:N relation

Given entities: Team, User. Relation between those is N:N.

Question: How do I find users which belong to specified teams (with given list of ids).

PS. I found how to do with single team, but have no clue how to deal with the list of teams?

var team_id = ...
QueryExpression query = new QueryExpression("user");

// setting up relation between teams and users
Relationship rel = new Relationship();
rel.SchemaName = "new_teams_users";

RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();
relatedEntity.Add(rel, query);

RetrieveRequest request = new RetrieveRequest();
request.RelatedEntitiesQuery = relatedEntity;
request.ColumnSet = new ColumnSet(new string[] {"id"});

request.Target = new EntityReference { Id = team_id, LogicalName = "new_team" };

// Results: List of users by team id.
RetrieveResponse response = (RetrieveResponse)CrmService.Execute(request);

Upvotes: 0

Views: 1834

Answers (2)

MarioZG
MarioZG

Reputation: 2087

QueryExpression build on intersect entity will help you. As example i used product and competitor N:N relationship

QueryExpression qe = new QueryExpression()
{
    EntityName = "competitorproduct",  //this name can be get from N:N rel properties (Relationship form, Relationship Entity Name field)
    ColumnSet = new ColumnSet(true),
};

qe.Criteria.AddCondition(
    "competitorid", 
    ConditionOperator.In, 
    new object[] { "GUID1", "GUID2"});

//Below is optional - if you need some details of entity, add LinkEntity object. This example adds all fields from product entity
LinkEntity lePorduct = new LinkEntity("competitorproduct", "product", "productid", "productid", JoinOperator.Inner);
lePorduct.Columns = new ColumnSet(true);
qe.LinkEntities.Add(lePorduct);

Upvotes: 3

Kevin Ross
Kevin Ross

Reputation: 7215

You would make your primary entity the intersection entity so in your example it would be "TeamMembership" the criteria would then be set against the attribute "SystemUserId".

To get more information on the team you need to add the team entity as a linked entity to your query like this

 LinkEntity TeamLink = new LinkEntity();
            TeamLink .EntityAlias = "TeamLink ";
            TeamLink .JoinOperator = JoinOperator.Inner;
            TeamLink .LinkFromEntityName = "teammembership";
            TeamLink .LinkFromAttributeName = "teamid";
            TeamLink .LinkToEntityName = "team";
            TeamLink .LinkToAttributeName = "teamid";

You can then bring back what ever columns you want and get the data out.

Upvotes: 0

Related Questions