简体   繁体   中英

Invalid Storage Type: DBNull

When using expando objects to fill my datatable, I am facing following error message when I initialize a new datarow . The exception is:

Invalid Storage Type: 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]

The value of the first result in your items[0] was DBNull.Vaue - which is what your SQL client populated into the structure. That's what the SQL client uses to indicate a null value. So, the actual type of the object in the first Value of the IDictionary<String,object> is DBNull ...not the type it would have been if there had been a value. You might have to iterate your dictionary until you get a value before you can add that column to the datarow...or come up with a more bulletproof way of assigning the type to the column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM