FetchXMLの柔軟性を楽しんでいるので、グリッドやリピーターなどへのバインドに使用するデータテーブルを返す次の関数を開発しました。
/// <summary>
/// Takes a CRM FetchXML query and returns a DataTable
/// </summary>
/// <param name="fetchXml">The FetchXML query</param>
/// <param name="requiredFields">A array of columns you'd expect returned. This is required as if there is no data for a field/column CRM will not return it which could impact databinding</param>
/// <returns>A datatable containing the results of the FetchXML</returns>
public static DataTable FetchXML2DataTable(string fetchXml, string[] requiredFields)
{
CrmService tomService = new CrmService();
tomService = CrmWebService;
string result = tomService.Fetch(fetchXml);
DataSet ds = new DataSet();
System.IO.StringReader reader = new System.IO.StringReader(result);
ds.ReadXml(reader);
DataTable dt = ds.Tables[1];
//check all required columns are present otherwise add them to make life easier for databinding at the top level
//caused by CRM not returning fields if they contain no data
foreach (string field in requiredFields)
{ //Check for column names and nested tables
if ((dt.Columns.IndexOf(field) < 0) && (dt.DataSet.Tables.IndexOf(field) <0))
{
//Add column to datatable even though it is empty for reason stated above
dt.Columns.Add(new DataColumn(field));
}
}
return dt;
}
結果セットにその列のデータが含まれていない場合は列が返されないため、requiredFields文字列配列がありますが、データグリッドなどにバインドする正確な理由から、列を配置する必要がある場合があります。
CrmServiceは、Webサービスを開始するシングルトンクラスです。
うまくいけば、これはあなたに役立つでしょう。