65.9K
CodeProject 正在变化。 阅读更多。
Home

将 EntityCollection 转换为 DataTable

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2013年2月26日

CPOL
viewsIcon

34323

将 DataTable 的 EntityCollection 转换为代码。

引言

此技巧提供了将 EntityCollection 转换为 DataTable 的代码。

使用代码

Dynamics CRM 2011 的 RetriveMultiple 方法返回一个 EntityCollection。以下代码是将该 EntityCollection 转换为 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;
}
© . All rights reserved.