你如何处理fetchxml结果数据?

Luk*_*lch 7 xml data-manipulation dynamics-crm fetchxml data-structures

我已经避免使用fetchxml,因为我一直不确定在调用crmService.Fetch(fetchXml)之后处理结果数据的最佳方法.在几种情况下,我使用带有LINQ的XDocument从此数据结构中检索数据,例如:

XDocument resultset = XDocument.Parse(_service.Fetch(fetchXml));
if (resultset.Root == null || !resultset.Root.Elements("result").Any())
{
    return;
}
foreach (var displayItem in resultset.Root.Elements("result").Select(item => item.Element(displayAttributeName)).Distinct())
{
    if (displayItem!= null && displayItem.Value != null)
    {
        dropDownList.Items.Add(displayItem.Value);    
    }
}
Run Code Online (Sandbox Code Playgroud)

处理fetchxml结果数据的最佳方法是什么,以便可以轻松使用.诸如将这些记录传递到ASP.NET数据网格之类的应用程序将非常有用.

Fis*_*ake 6

我喜欢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;
    }
Run Code Online (Sandbox Code Playgroud)

requiredFields字符串数组在那里,因为如果您的结果集不包含该列的数据,则不会返回列,但是我可能希望该列用于绑定到datagrids等的确切原因.

CrmService是一个启动Web服务的单例类.

希望这对你有用.


bre*_*dan 1

正是因为这个原因,我通常会避免使用 FetchXML。您可以使用 RetrieveMultiple 获取强类型 BusinessEntity 对象,并且基本上执行相同的操作。

但如果您想使用 FetchXML,此示例应该可以满足您的要求:

http://msdn.microsoft.com/en-us/library/ms914457.aspx