如何使用查询表达式crm进行内部连接

时间:2012-11-15 12:18:38

标签: sql-server dynamics-crm-2011 query-expressions

我正在尝试使用Query Expression进行简单的内部联接。我试图用QE转换这个查询,但我总是得到同样的错误。我正在做这个QE:

Entity Role = new Entity();
Role.LogicalName = "role";

Entity SystemUserRoles = new Entity();
SystemUserRoles.LogicalName = "systemuserroles";

QueryExpression query = new QueryExpression() {
  Distinct = false, EntityName = Role.LogicalName, ColumnSet = new ColumnSet("name"),

  LinkEntities = {
    new LinkEntity {
      JoinOperator = JoinOperator.Inner, LinkFromAttributeName = "roleid", LinkFromEntityName = Role.LogicalName, LinkToAttributeName = "roleid", LinkToEntityName = SystemUserRoles.LogicalName,
    }
  },

  Criteria = {
    Filters = {
      new FilterExpression {
        FilterOperator = LogicalOperator.And, Conditions = {
          new ConditionExpression("systemuserid", ConditionOperator.Equal, "9b1bf31d-ac29-e211-9826-00155d0a0b0f"),

        },
      },

    }
  }
};

ret = _service.RetrieveMultiple(query);

得到这个:

SELECT b.Name
  FROM Role b
   INNER JOIN SystemUserRoles a
   ON a.RoleId=b.RoleId  
    WHERE SystemUserId = '9b1bf31d-ac29-e211-9826-00155d0a0b0f'  

但这告诉我实体Role不包含字段SystemUserId。有什么想法吗?

1 个答案:

答案 0 :(得分:10)

您的Condition Expression需要继续使用LinkCriteria对象。实际上,这是您当前查询的转换方式。

SELECT b.Name
FROM Role b
INNER JOIN SystemUserRoles a
ON a.RoleId=b.RoleId  
WHERE b.SystemUserId = '9b1bf31d-ac29-e211-9826-00155d0a0b0f'  

尝试此查询表达式:

Entity role = new Entity();
role.LogicalName = "role";

Entity systemUserRoles = new Entity();
systemUserRoles.LogicalName = "systemuserroles";

QueryExpression query = new QueryExpression() {
  Distinct = false, EntityName = role.LogicalName, ColumnSet = new ColumnSet("name")
};

query.AddLink( systemUserRoles.LogicalName, "roleid", "roleid").
LinkCriteria.AddCondition("systemuserid", ConditionOperator.Equal, "9b1bf31d-ac29-e211-9826-00155d0a0b0f");

ret = _service.RetrieveMultiple(query);

注意如何将条件添加到链接上的LinkCriteria而不是查询表达式本身?

更新1

正如@JamesWierzba所指出的那样,没有理由定义一个实体只是为了使用它的逻辑名称:

QueryExpression query = new QueryExpression() {
  Distinct = false, EntityName = "role", ColumnSet = new ColumnSet("name")
};

query.AddLink("systemuserroles", "roleid", "roleid").
LinkCriteria.AddCondition("systemuserid", ConditionOperator.Equal, "9b1bf31d-ac29-e211-9826-00155d0a0b0f");

ret = _service.RetrieveMultiple(query);

如果你使用DLaB.Xrm Nuget Package,你可以更简洁地写出来:

var qe = QueryExpressionFactory.Create("role", "name");
qe.AddLink("systemuserroles", "roleid")
  .WhereEqual("systemuserid", "9b1bf31d-ac29-e211-9826-00155d0a0b0f");

ret = _service.RetrieveMultiple(qe);