使用 FetchXML 构建查询
发布日期: 2017年1月
适用于: Dynamics 365 (online),Dynamics 365 (on-premises),Dynamics CRM 2016,Dynamics CRM Online
若要在 Microsoft Dynamics 365 和 Microsoft Dynamics 365 (online) 中执行 FetchXML 查询,必须首先生成 XML 查询字符串。 创建查询字符串后,使用 IOrganizationService.RetrieveMultiple 方法执行查询字符串。 登录用户的特权影响返回的记录集。 将仅返回登录用户对其具有读取访问权限的记录。
FetchXML 查询字符串必须符合 FetchXML 语言的架构定义。 有关详细信息,请参阅FetchXML schema。
您可以通过创建 SavedQuery 记录保存查询,如示例:验证和执行已保存查询中所示。 将 link-entity 节点上的 visible 设置为 false 可隐藏“高级查找”用户界面中的链接实体。 它仍会参与执行查询,且返回相应的结果。
警告
不要在查询中检索所有属性,否则会对性能造成负面影响。 当查询用作更新请求的参数时,尤其如此。 在更新中,如果包括所有属性,则它会设置所有字段值(即使它们没有更改),且触发器通常将更新级联到子记录。
创建查询字符串
在下面的示例中,FetchXML 语句检索所有客户:
<fetch mapping='logical'>
<entity name='account'>
<attribute name='accountid'/>
<attribute name='name'/>
</entity>
</fetch>
在下面的示例中,FetchXML 语句检索负责用户的姓氏不是 Cannon 的所有帐户:
<fetch mapping='logical'>
<entity name='account'>
<attribute name='accountid'/>
<attribute name='name'/>
<link-entity name='systemuser' to='owninguser'>
<filter type='and'>
<condition attribute='lastname' operator='ne' value='Cannon' />
</filter>
</link-entity>
</entity>
</fetch>
在以下示例中,FetchXML 语句使用计数设置从查询返回的最大记录数。 在此方案中,从查询返回前 3 个帐户。
<fetch mapping='logical' count='3'>
<entity name='account'>
<attribute name='name' alias='name'/>
</entity></fetch>
此示例显示在 EntityMap 和 EntityMapID 匹配的 AttributeMap 之间的内联。
<fetch version='1.0' mapping='logical' distinct='false'>
<entity name='entitymap'>
<attribute name='sourceentityname'/>
<attribute name='targetentityname'/>
<link-entity name='attributemap' alias='attributemap' to='entitymapid' from='entitymapid' link-type='inner'>
<attribute name='sourceattributename'/>
<attribute name='targetattributename'/>
</link-entity>
</entity>
</fetch>
执行查询
下面的代码演示如何执行 FetchXML 查询:
// Retrieve all accounts owned by the user with read access rights to the accounts and
// where the last name of the user is not Cannon.
string fetch2 = @"
<fetch mapping='logical'>
<entity name='account'>
<attribute name='accountid'/>
<attribute name='name'/>
<link-entity name='systemuser' to='owninguser'>
<filter type='and'>
<condition attribute='lastname' operator='ne' value='Cannon' />
</filter>
</link-entity>
</entity>
</fetch> ";
EntityCollection result = _serviceProxy.RetrieveMultiple(new FetchExpression(fetch2));foreach (var c in result.Entities) { System.Console.WriteLine(c.Attributes["name"]); }
查询结果
使用 RetrieveMultiple 方法执行 FetchXML 查询时,返回值是包含查询结果的 EntityCollection。 然后可以循环访问实体集合。 上一示例使用 foreach 循环来循环访问 FetchXML 查询的结果集合。
另请参阅
使用 FetchXML 构建查询
使用 FetchXML 聚合
FetchXML schema
Microsoft Dynamics 365
© 2017 Microsoft。 保留所有权利。 版权