处理DBnull执行的最佳方法是什么?

时间:2019-07-16 21:32:42

标签: c# sql asp.net-core asp.net-web-api ado

我有一些项目从数据库中返回DBnull,这引发了异常。处理异常的最佳方法是什么?更具体地说,适用于Daily和EndDate。 Daily是sql中的一位数据类型,EndDate是DateTime。这是我当前实现的代码的方式。

while (reader.Read())
                {
                    sessionInfo.ID = sessionId;
                    sessionInfo.Name = Convert.ToString(reader["Name"]);
                    sessionInfo.GroupID = Convert.ToString(reader["GroupId"]);
                    sessionInfo.Disabled = Convert.ToBoolean(reader["IsDisabled"]);
                    sessionInfo.IsTestSession = Convert.ToBoolean(reader["IsTestSession"]);
                    sessionInfo.NextTrigger = reader["NextExecutionTime"] == DBNull.Value ? null : (DateTime?)reader["NextExecutionTime"];
                    sessionInfo.Type = Convert.ToString(reader["SType"]);
                    sessionInfo.POKeepDays = Convert.ToInt32(reader["DaysToKeep"]);
                    sessionInfo.When = new SchedulerInfo()
                    {
                        ID = sessionId,
                        SessionID = sessionId,
                        //TODO Recurrence = 
                        //TODO MultiTriggerTimes
                        //TODO MultiTriggerColl                          
                        MinuteFreq = Convert.ToString(reader["MinuteFreq"]),
                        HourFreq = Convert.ToString(reader["HourFreq"]),
                        Daily = reader.GetBoolean(reader.GetOrdinal("Daily")),
                        WeekFreq = Convert.ToString(reader["WeekFreq"]),
                        StartDate = Convert.ToDateTime(reader["StartDate"]),
                        EndDate = Convert.ToDateTime(reader["EndDate"]),
                        NoOrderDays = Convert.ToString(reader["NoOrderDays"]),
                        OrderDays = Convert.ToString(reader["OrderDays"]),
                        SelectedHolidays = Convert.ToString(reader["NoOrderHoliday"]),
                        SelectedOrderHolidays = Convert.ToString(reader["HolidayName"]),

我希望学习如何最好地处理为BdNull值引发的异常

1 个答案:

答案 0 :(得分:0)

  • 避免使用Convert.ToFoo,而应直接在GetFoo上使用DataReader方法。
  • 如果您首先使用DataReader.IsDBNull(),那么您首先不会获得与DBNull相关的异常。

像这样:

while (reader.Read())
{
    sessionInfo.ID = sessionId;
    sessionInfo.Name = reader.IsDBNull( "Name" ) ? null : reader.GetString( "Name" );
    sessionInfo.GroupId = reader.IsDBNull( "GroupId" ) ? null : reader.GetString( "GroupId" );
    sessionInfo.Disabled = reader.IsDBNull( "Disabled" ) ? false : reader.GetBoolean( "Disabled" );
    // etc...