输入数组是否长于此表中的列数?

Kyl*_*Ren -9 c# datatable

我今天整天都在收到这个错误,我看不出它是怎么发生的?我正在制作一个DataTable,它有7列,但是当我尝试将数组添加到表中时,我得到了错误.

这是代码;

    public static void BulkEntityInsert<T>(this T entity, List<T> entities)
    {
        //give array lenght
        string[] columns = new string[7];          

        DataTable dataTable = new DataTable();
        try
        {
            int jj = 0;
            DataColumn datecolumn = new DataColumn();
            foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(entity))
            {
                datecolumn.AllowDBNull = true;
                datecolumn.ColumnName = prop.Name == "Id" ? "ID" : prop.Name;
                datecolumn.DataType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
                columns[jj] = prop.Name == "Id" ? "ID" : prop.Name;                    
                jj++;
            }

            foreach (T t in entities)
            {
                // give the record array the same length as the columns variable
                object[] record = new object[columns.Length];

                int j = 0;
                foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(t))
                {
                    record[j] = prop.GetValue(t);
                    j++;
                }
                // Errror occurs here
                dataTable.Rows.Add(record);
            }
            // Save data to DB
            SqlBulkCopyInsert(dataTable);
        }
        catch (Exception ex)
        {
            MessageBox.Show("DataTable was not correctly made", ex.Message);
        }           
    }
Run Code Online (Sandbox Code Playgroud)

任何帮助解决这个问题将非常感激.

编辑:只是碰到更多的downvotes.

Tim*_*ter 5

您只有一列,而不是将其添加到DataTable:

DataColumn datecolumn = new DataColumn();
foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(entity))
{
    datecolumn.AllowDBNull = true;
    datecolumn.ColumnName = prop.Name == "Id" ? "ID" : prop.Name;
    datecolumn.DataType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
    columns[jj] = prop.Name == "Id" ? "ID" : prop.Name;                    
    jj++;
}
Run Code Online (Sandbox Code Playgroud)

相反,你必须在循环中创建它们然后添加它们(循环体中的最后一行):

foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(entity))
{
    DataColumn datecolumn = new DataColumn();
    datecolumn.AllowDBNull = true;
    datecolumn.ColumnName = prop.Name == "Id" ? "ID" : prop.Name;
    datecolumn.DataType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
    columns[jj] = prop.Name == "Id" ? "ID" : prop.Name;                    
    jj++;

    dataTable.Columns.Add(datecolumn);
}
Run Code Online (Sandbox Code Playgroud)