65.9K
CodeProject is changing. Read more.
Home

Convert EntityCollection to DataTable

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Feb 26, 2013

CPOL
viewsIcon

34170

Code for converting the EntityCollection of a DataTable.

Introduction

This tips gives code for converting the EntityCollection of a DataTable.

Using the code

The Dynamics CRM 2011 RetriveMultiple method returns an EntityCollection. The below code is to convert th EntityCollection to a DataTable.

//Get records returns the Entity Collection
public DataTable GetDataTable()
{
    EntityCollection accountRecords = GetAccountRecords();
    DataTable dTable = new DataTable();
    int iElement = 0;

    if (accountRecords.Entities.Count >= 0)
    {
        return;
    }

    //Defining the ColumnName for the datatable
    for (iElement = 0; iElement <= accountRecords.Entities[0].Attributes.Count - 1; iElement++)
    {
        string columnName = accountRecords.Entities[0].Attributes.Keys.ElementAt(iElement);
        dTable.Columns.Add(columnName);
    }

    foreach (Entity entity in accountRecords.Entities)
    {
        DataRow dRow = dTable.NewRow();
        for (int i = 0; i <= entity.Attributes.Count - 1; i++)
        {
            string colName = entity.Attributes.Keys.ElementAt(i);
            dRow[colName] = entity.Attributes.Values.ElementAt(i);
        }
        dTable.Rows.Add(dRow);
    }
    return dTable;
}