开发者

GetSchemaTable Columns Missing?

开发者 https://www.devze.com 2023-04-09 08:21 出处:网络
I am using this code to get data from a dataReader into a DataTable which ca开发者_Python百科n then be serialised.

I am using this code to get data from a dataReader into a DataTable which ca开发者_Python百科n then be serialised.

However, it looks like any column with a null value isnt being written to the xml.

I cant see the issue.

This is my entire class, and im calling this method

Process(IDataReader data, string filePath)

Im certain that this works, because i have used it to serialise dataTables before

Process(DataTable table, string filePath)

So i think it must be in the "GetDataTableFromSqlDataReader" method??

public class DataSerialisation
{
    public static DataRow GetFirstDataRow(string xmlFilePath)
    {
        return GetDataTable(xmlFilePath).Rows[0];
    }

    public static DataTable GetDataTable(string xmlFilePath)
    {
        DataSet ds = new DataSet();
        ds.ReadXml(xmlFilePath);
        return ds.Tables[0];
    }

    private static DataTable GetDataTableFromSqlDataReader(IDataReader dr)
    {

        DataTable dtSchema = dr.GetSchemaTable();
        DataTable dt = new DataTable();
        ArrayList listCols = new ArrayList();
        if (dtSchema != null)
        {
            foreach (DataRow drow in dtSchema.Rows)
            {
                string columnName = Convert.ToString(drow["columnName"]); //drow["columnName"].ToString();

                DataColumn column = new DataColumn(columnName, (Type) (drow["DataType"]));
                //column.ColumnName = columnName;
                //column.Unique = (bool) (drow["IsUnique"]);
                column.AllowDBNull = (bool) (drow["AllowDBNull"]);
                //column.AutoIncrement = (bool) (drow["IsAutoIncrement"]);
                //column.AutoIncrement = (bool) (drow["IsAutoIncrement"]);

                listCols.Add(column);
                dt.Columns.Add(column);
            }
            while (dr.Read())
            {
                DataRow dataRow = dt.NewRow();
                for (int i = 0; i < listCols.Count; i++)
                    dataRow[((DataColumn) listCols[i])] = dr[i];

                dt.Rows.Add(dataRow);
            }
        }
        return dt;
    }

    public static void Process(IDataReader data, string filePath)
    {
        Process(GetDataTableFromSqlDataReader(data), filePath);
    }

    public static void Process(DataTable table, string filePath)
    {
        DataSet ds = new DataSet();

        ds.Tables.Add(table.Clone());

        foreach (DataRow row in table.Rows)
        {
            DataRow newRow = ds.Tables[0].NewRow();
            for (int col = 0; col < ds.Tables[0].Columns.Count; col++)
                newRow[col] = row[col];
            ds.Tables[0].Rows.Add(newRow);
        }
        ds.WriteXml(new StreamWriter(filePath));
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消