Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Convert BusinessEntityCollection to a DataTable

4.00/5 (1 vote)
14 Sep 2009CPOL 30.6K   511  
Convert an MS Dynamics CRM 4 BusinessEntityCollection to a DataTable.

Introduction

MS Dynamics CRM 4 returns data in a response object containing a BusinessEntityCollection. This code converts this BusinessEntityCollection into a simple .NET DataTable.

Using the code

For every property found in BusinessEntityCollection's each row, it checks if the DataTable already contains a column with that name. If the DataTable doesn't contain it, the function adds it to the DataTable and restarts traversing the currently selected row.

C#
public DataTable convertBuinessEntityCollectionToDataTable(BusinessEntityCollection BEC)
{
    DataTable dt = new DataTable();
    int total = BEC.BusinessEntities.Length;
    //////////////////////////////////////////////////////////////////////////
    bool continueFlag = false;
    for (int i = 0; i < total; i++)
    {
        DataRow row = dt.NewRow();
        DynamicEntity myEntity = (DynamicEntity)BEC.BusinessEntities[i];
        for (int j = 0; j < myEntity.Properties.Length; j++)
        {
            Property pp;
            pp = myEntity.Properties[j];
            string columnName = pp.Name;
            string value = getNameFromProperty(pp);
            if (dt.Columns.IndexOf(columnName) == -1)
            {
                dt.Columns.Add(pp.Name, Type.GetType("System.String"));
                i--;
                continueFlag = true;
                break;
            }
            else
            {
                continueFlag=false;
            }
            row[columnName] = value;
        }
        if (continueFlag == true)
        {
            continue;
        }
        dt.Rows.Add(row);
    }
    /////////////////////////////////////////////////////////////////////////
    return dt;
}

The code above calls a function getNameFromProperty() which can be found inside the attached zip file.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)