通过N:N关系中的多个ID获取实体

时间:2013-10-16 07:13:48

标签: dynamics-crm-2011 crm

给定实体: 团队,用户。它们之间的关系是N:N。

问题: 如何查找属于指定团队的用户(使用给定的ID列表)。

PS。 我发现如何处理单个团队,但不知道如何处理团队列表?

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);

2 个答案:

答案 0 :(得分:3)

在交叉实体上构建QueryExpression会对你有所帮助。例如,我使用产品和竞争对手N:N关系

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);

答案 1 :(得分:0)

您可以将您的主要实体设为交叉点实体,因此在您的示例中,它将是" TeamMembership"然后根据属性" SystemUserId"。

设置标准

要获得有关团队的更多信息,您需要将团队实体作为链接实体添加到您的查询中

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

然后,您可以恢复所需的列,并获取数据。