使用 FetchXML 建構查詢
發行︰ 2016年11月
適用於: Dynamics CRM 2015
若要在執行 Microsoft Dynamics CRM 2015 和 Microsoft Dynamics CRM 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>
執行查詢
下列程式碼顯示如何執行 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
© 2017 Microsoft. 著作權所有,並保留一切權利。 著作權