7

我正在尝试使用查询表达式进行简单的内部连接。我试图用 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'  

但这告诉我实体角色不包含该字段SystemUserId。任何的想法?

4

1 回答 1

12

您的条件表达式需要在 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 包,您可以更简洁地编写它:

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

ret = _service.RetrieveMultiple(qe);
于 2012-11-15T13:31:35.580 回答