我今天一整天都收到这个错误,我看不出它是怎么发生的?我正在制作一个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);
}
}
非常感谢任何解决此问题的帮助。
编辑:只是碰到更多的downvotes。
答案 0 :(得分: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++;
}
相反,你必须在循环中创建它们然后添加它们(循环体中的最后一行):
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);
}