C# DataReader To DataSet(多用于ORM框架底层实现)

        [SecurityCritical]
        [SecuritySafeCritical]
        public DataSet ToDataSet(DbDataReader dataReader)
        {
            if (dataReader == null)
            {
                return null;
            }
            DataSet dataSet = new DataSet();
            if (!dataReader.HasRows)
            {
                dataSet.Tables.Add(new DataTable());
                return dataSet;
            }
            for (; ; )
            {
                DataTable dataTable = new DataTable();
                try
                {
                    int fieldCount = dataReader.VisibleFieldCount;
                    for (int i = 0; i < fieldCount; i++)
                    {
                        string fieldName = dataReader.GetName(i);
                        Type fieldType = dataReader.GetFieldType(i);
                        dataTable.Columns.Add(new DataColumn(fieldName, fieldType));
                    }
                    while (dataReader.Read())
                    {
                        object[] rowValues = new object[fieldCount];
                        dataReader.GetValues(rowValues);
                        dataTable.Rows.Add(rowValues);
                    }
                    dataSet.Tables.Add(dataTable);
                    if (!dataReader.NextResult())
                    {
                        return dataSet;
                    }
                }
                catch (Exception)
                {
                    foreach (DataTable p in dataSet.Tables)
                    {
                        try
                        {
                            p?.Dispose();
                        }
                        catch (Exception) { }
                    }
                    try
                    {
                        dataTable.Dispose();
                    }
                    catch (Exception) { }
                    try
                    {
                        dataSet.Dispose();
                    }
                    catch (Exception) { }
                    return null;
                }
            }
        }

上一篇:c# 下 根据Datatable的结构动态创建表


下一篇:DataSet / BindingSource / DataGridView / BindingNavigator 的关系与绑定、修改数据库