SqlDataReader to IList<T>

本文介绍了一个实用的方法,将SQLDataReader中的数据转换为IList&lt;T&gt;集合,支持多种数据类型的自动转换,并妥善处理了空值的情况。
    #region SqlDataReader to IList<T>


        public static IList<T> SqlDataReaderToIList<T>(SqlDataReader sqldatareader)
        {
            try
            {
                IList<T> list = new List<T>();
                while (sqldatareader.Read())
                {
                    T t = System.Activator.CreateInstance<T>();
                    Type type = t.GetType();
                    for (int i = 0; i < sqldatareader.FieldCount; i++)
                    {
                        object TempValue = null;
                        if (sqldatareader.IsDBNull(i))
                        {
                            string typeFullName = type.GetProperty(sqldatareader.GetName(i)).PropertyType.FullName;
                            TempValue = GetDbNullValue(typeFullName);
                        }
                        else
                        {
                            TempValue = sqldatareader.GetValue(i);
                        }
                        type.GetProperty(sqldatareader.GetName(i)).SetValue(t, TempValue, null);
                    }
                    list.Add(t);


                }
                return list;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                sqldatareader.Close();
                sqldatareader.Dispose();
            }




        }


        private static object GetDbNullValue(string typeFullName)
        {
            typeFullName = typeFullName.ToLower();
            if (typeFullName == "string")
                return string.Empty;
            else if (typeFullName == "int32" || typeFullName == "int16" || typeFullName == "int64")
                return 0;
            else if (typeFullName == "datetime")
                return Convert.ToDateTime(DateTime.MinValue);
            else if (typeFullName == "boolean")
                return false;
            else if (typeFullName == "int")
                return 0;
            return null;
        }


        #endregion
System.Data.SqlTypes.SqlTypeException HResult=0x80131930 Message=SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM. Source=System.Data.Common StackTrace: 在 System.Data.SqlTypes.SqlDateTime.FromTimeSpan(TimeSpan value) 在 System.Data.SqlTypes.SqlDateTime.FromDateTime(DateTime value) 在 System.Data.SqlTypes.SqlDateTime..ctor(DateTime value) 在 Microsoft.Data.SqlClient.MetaType.FromDateTime(DateTime dateTime, Byte cb) 在 Microsoft.Data.SqlClient.TdsParser.WriteUnterminatedValue(Object value, MetaType type, Byte scale, Int32 actualLength, Int32 encodingByteSize, Int32 offset, TdsParserStateObject stateObj, Int32 paramSize, Boolean isDataFeed) 在 Microsoft.Data.SqlClient.TdsParser.WriteValue(Object value, MetaType type, Byte scale, Int32 actualLength, Int32 encodingByteSize, Int32 offset, TdsParserStateObject stateObj, Int32 paramSize, Boolean isDataFeed) 在 Microsoft.Data.SqlClient.TdsParser.TDSExecuteRPCAddParameter(TdsParserStateObject stateObj, SqlParameter param, MetaType mt, Byte options, SqlCommand command, Boolean isAnonymous) 在 Microsoft.Data.SqlClient.TdsParser.TdsExecuteRPC(SqlCommand cmd, IList`1 rpcArray, Int32 timeout, Boolean inSchema, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, Boolean isCommandProc, Boolean sync, TaskCompletionSource`1 completion, Int32 startRpc, Int32 startParam) 在 Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) 在 Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method) 在 Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) 在 Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior) 在 Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) 在 Dapper.SqlMapper.ExecuteReaderWithFlagsFallback(IDbCommand cmd, Boolean wasClosed, CommandBehavior behavior) 在 Dapper.SqlMapper.<QueryImpl>d__149`1.MoveNext() 在 System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) 在 System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) 在 Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) 在 StudentWeb.DAL.PjjUserInfoDAO.Insert(PjjUserInfo pjjUserInfo, IDbTransaction trans) 在 I:\StudentWeb\StudentWeb.Data\DAL\PjjUserInfoDAO.cs 中: 第 38 行 在 StudentWeb.BLL.PjjBO.Insert(PjjInfo model) 在 I:\StudentWeb\StudentWeb\BLL\PjjBO.cs 中: 第 76 行 在 StudentWeb.Controllers.PjjController.Insert(PjjInfo model) 在 I:\StudentWeb\StudentWeb\Controllers\PjjController.cs 中: 第 53 行 在 Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync() 在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
11-13
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值