2014-10-28 143 views
1

我需要將null插入類字段datetime? 這是類:如何插入DBnull爲可空的DateTime字段asp.net c#

public class TimeData{ 
     public int TD_ID { get; set; } 
     public int UD_ID { get; set; } 
     public DateTime? TD_start { get; set; } 
     public DateTime? TD_end { get; set; } 
     public DateTime? timestemp { get; set; } 

    public void Insert(int TD_ID, int UD_ID, DateTime? TD_start, DateTime? TD_end, DateTime? timestemp) 
    { 
     this.TD_ID=TD_ID; 
     this.UD_ID = UD_ID; 
     this.TD_start = TD_start; 
     this.TD_end = TD_end; 
     this.timestemp = timestemp; 

    } 
} 

我使用從網頁存儲過程了對SQL服務器的訪問。 datetime字段的一些返回值爲空,並返回爲DBnull,它不能存儲在DateTime中? 我可以用很多if檢查返回值,但我更喜歡找到更優雅的方式使其工作。 SQL Server連接:

try 
       { 
        String strConnString = ConfigurationManager.ConnectionStrings["Achi"].ConnectionString; 
        System.Data.SqlClient.SqlConnection SQLCon = new System.Data.SqlClient.SqlConnection(); 
        SqlDataReader myReader = default(SqlDataReader); 
        SQLCon = new SqlConnection(strConnString); 
        SqlCommand sqlCmd = new SqlCommand("usp_TD_select_last_record_By_UD_ID", SQLCon); 
        sqlCmd.Parameters.AddWithValue("@UD_ID", user.UD_ID); 
        sqlCmd.CommandType = CommandType.StoredProcedure; 
        SQLCon.Open(); 
       if (SQLCon.State == ConnectionState.Open) 
       { 
        myReader = sqlCmd.ExecuteReader(); 

        if (myReader.HasRows) 
        { 
         while (myReader.Read()) 
         { 
          timeData.Insert(Convert.ToInt32(myReader["TD_ID"].ToString()), Convert.ToInt32(myReader["UD_ID"].ToString()), Convert.ToDateTime(myReader["TD_start"]), Convert.ToDateTime(myReader["TD_end"]), Convert.ToDateTime(myReader["TD_timestemp"])); 

         } 
        } 
        else { newLine = true; } 
        myReader.Close(); 
        SQLCon.Close(); 
       } 
      } 
      catch (Exception ex) 
      { 
       throw ex; 
      } 

和表在數據庫中的模樣說:

[TD_ID] [int] IDENTITY(1,1) NOT NULL, 
[UD_ID] [int] NULL, 
[TD_start] [datetime] NULL, 
[TD_end] [datetime] NULL, 
[TD_timestemp] [datetime] NULL, 

回答

0

你可以有一個輔助函數是這樣的:

public static T GetValue<T>(this IDataRecord record, string name) 
{ 
    var index = record.GetOrdinal(name); 
    return record.IsDBNull(index) ? default(T) : (T)record.GetValue(index); 
} 

然後調用它:

timeData.Insert(myReader.GetValue<int>("TD_ID"), 
       .... myReader.GetValue<DateTime?>("TD_timestemp"), ...); 
+0

謝謝!工作很棒 – 2014-10-28 15:05:13

0

我想轉換爲日期時間,當你得到了一些類型的異常。考慮使用Convert.IsDBNull方法。你的情況,你可以做這樣的:

Convert.IsDBNull(myReader["TD_start"]) ? (DateTime?)null : Convert.ToDateTime(myReader["TD_start"]) 
1
this.TD_start = (myReader["TD_start"] == DBNull.Value) ? 
       (DateTime?)null : Convert.ToDateTime(myReader["TD_start"]); 
相關問題