我喜欢 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 服务的单例类。
希望这对你有用。