2

当使用 expando 对象填充我的数据表时,我在初始化一个新的datarow. 例外是:

无效的存储类型:DBNull

public static DataTable ToCLDataTable<T>(List<T> items)
{
    DataTable dataTable = new DataTable("CLWorkQueue");
    //Get all the properties
    DataRow dr;

    var expandoDict = items[0] as IDictionary<string, object>;
    foreach (var key in expandoDict.Keys)
    {
        if ((expandoDict[key]).GetType() == typeof(DateTime))
        {
            dataTable.Columns.Add(key.ToString(), typeof(DateTime));
        }
        else
        {
            dataTable.Columns.Add(key.ToString(), expandoDict[key].GetType());
        }
    }

    for (int i = 0; i < items.Count; i++)
    {
        var expandoDictData = items[i] as IDictionary<string, object>;
        //var values = new object[expandoDictData.Count];
        int j = 0;
        dr = dataTable.NewRow(); /*Though the datatable has all the required columns, but whenever i try to initialize a new row an exception occurs.*/
        foreach (var key in expandoDictData.Keys)
        {
            //values[j] = expandoDictData[key].ToString();
            dr[key] = expandoDictData[key].ToString();
            j++;
        }
        dataTable.Rows.Add(dr);
        //dataTable.Rows.Add(values);
    }[enter image description here][1]
4

1 回答 1

1

您的第一个结果的值items[0]DBNull.Vaue - 这是您的 SQL 客户端填充到结构中的值。这就是 SQL 客户端用来指示空值的方法。所以,第一个对象的实际类型是......不是如果有一个值它本来应该是的类型。您可能必须迭代您的字典,直到获得一个值,然后才能将该列添加到数据行......或者想出一种更安全的方法来将类型分配给列。ValueIDictionary<String,object>DBNull

于 2016-05-04T15:22:16.850 回答