编程语言
首页 > 编程语言> > C# DataReader To DataSet(多用于ORM框架底层实现)

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;
                }
            }
        }

标签:Exception,dataReader,C#,dataSet,DataReader,new,DataSet,dataTable
来源: https://blog.csdn.net/liulilittle/article/details/120434152