我有一些项目从数据库中返回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值引发的异常
答案 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...