65.9K
CodeProject is changing. Read more.
Home

Convert BusinessEntityCollection to a DataTable

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1 vote)

Sep 14, 2009

CPOL
viewsIcon

30583

downloadIcon

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.

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.