2012-03-29 61 views
3

我有下面的代码无效的转换日期时间?

public cCase(string pCaseNo, string pMode) 
    { 
     if (pMode == "new") 
     { 
      this._caseNo = Validate_CaseNo(pCaseNo); 
     } 
     if (pMode == "existing") 
     { 
      try 
      { 
       int intValidatedCaseNo = Validate_CaseNo(pCaseNo); 
       string sqlText = "SELECT * FROM tblCases WHERE CaseNo = @CaseNo;"; 
       string strConnection = cConnectionString.BuildConnectionString(); 
       SqlConnection linkToDB = new SqlConnection(strConnection); 
       linkToDB.Open(); 
       SqlCommand sqlCom = new SqlCommand(sqlText, linkToDB); 
       sqlCom.Parameters.Add("@CaseNo", SqlDbType.Int); 
       sqlCom.Parameters["@CaseNo"].Value = intValidatedCaseNo; 
       SqlDataReader caseReader = sqlCom.ExecuteReader(); 
       if (caseReader.HasRows) 
        while (caseReader.Read()) 
        { 
         this._claimant = caseReader["Claimant"].ToString(); 
         this._defendant = caseReader["Defendant"].ToString(); 
         this._caseType = caseReader["CaseType"].ToString(); 
         this._occupation = caseReader["Occupation"].ToString(); 
         this._doa = (DateTime?)caseReader["DOA"]; 
         this._dateClosed = (DateTime?)caseReader["DateClosed"]; 
         this._dateSettled = (DateTime?)caseReader["DateSettled"]; 
         this._dateInstructed = (DateTime?)caseReader["DateInstructed"]; 
         this._status = caseReader["Status"].ToString(); 
         this._instructionType = caseReader["InstructionType"].ToString(); 
         this._feeEstimate = (decimal?)caseReader["FeeEstimate"]; 
         this._amountClaimed = (decimal?)caseReader["AmountClaimed"]; 
         this._amountSettled = (decimal?)caseReader["AmountSettled"]; 
         this._caseManager = caseReader["CaseManager"].ToString(); 
        } 
       caseReader.Close(); 
       linkToDB.Close(); 
       linkToDB.Dispose(); 
      } 
      catch (Exception eX) 
      { 
       throw new Exception("Error finding case" + Environment.NewLine + eX.Message); 
      } 
     } 
    } 

然而,日期时间的一类?剧组失败并带有“无效投射”。 我检查了SQL数据库和该字段存储有效日期 所以我不能解决为什么,因为我通过DataReader将信息提取到我的应用程序中,日期时间字段导致无效投射。

请帮助。

+0

'caseReader'持有什么类型? – ChrisF 2012-03-29 12:30:04

+2

你的DateTime字段中的一个可能包含一个DBNull - 据我所知,你不能直接从DBNull转换为Nullable类型。然而,这种情况下有扩展。 – Alex 2012-03-29 12:32:06

+0

除了关于空值的其他答案 - 您说该字段正在存储有效日期,但它是否使用适当的数据类型(例如'datetime','datetime2'或'date')来存储它们? – 2012-03-29 12:35:09

回答

6

你会想更改读取的行:

this._doa = (DateTime?)caseReader["DOA"]; 

到:

if (caseReader["DOA"] != DBNull.Value) 
    this._doa.Value = (DateTime)caseReader["DOA"]; 

以及所有类似的路线。

DBNull值不能从Nullable类型转换。

+0

试过这个,但它说DBNull是一个类型,但它使用像一个变量?! – PJW 2012-03-29 12:45:47

+0

对不起。试试DBNull.Value。看我的编辑。 – Khan 2012-03-29 12:49:15

0

尝试用下面的代码部分

this._doa = (caseReader["DOA"] == DBNull.Value ? DBNull.Value : Convert.ToDateTime(caseReader["DOA"]); 
+0

为什么只将值转换为字符串来执行空检查? – 2012-03-29 12:40:15

+0

@Damien_The_Unbeliever,我改变了它。但是,我不仅检查了空值,而且也检查了空值。 – 2012-03-29 12:41:36

3

DateTime领域可能持有DBNull值,你不能直接转换。

但是,为了方便起见,我会在DataReader上使用扩展方法。

public static class DataReaderExtensions 
{ 
    public static DateTime? ReadNullableDateTime(this IDataReader reader, string column) 
    { 
     return reader.IsDBNull(column) ? (DateTime?)null : reader.GetDateTime(column); 
    } 
} 

//使用

this._dateInstructed = CaseReader.ReadNullableDateTime("DateInstructed"); 
+0

+1伟大的可重复使用的解决方案。 – Khan 2012-03-29 12:40:33

+1

信用实际上去马克,他有想法用扩展包装它们http://stackoverflow.com/a/9464730/1028323 – Alex 2012-03-29 12:43:48

+0

这是因为他与查克诺里斯有关。 – Khan 2012-03-29 13:19:39

0

尝试转换日期时间为

this._doa = Convert.ToDateTime(caseReader["DOA"]); 
+0

如果caseReader [“DOA”]是DBNull.Value将会发出异常。 – Dummy01 2012-03-29 12:43:34

0

我经常处理DBNull.Value ...

所以我用这个方法将返回如果对象的值为,则该对象的值或给定值类型的默认值。

public static object GetValueOrDefault(object value, Type type) 
    { 
     if (value != DBNull.Value) 
      return value; 

     if (type.IsValueType == false) 
      return null; 

     Array array = Array.CreateInstance(type, 1); 

     return array.GetValue(0); 
    } 

用法:

GetValueOrDefault(dataRecord.GetValue(fieldIndex), dataRecord.GetFieldType(fieldIndex) 
2

您应该使用

DateTime.TryParse Method

这不会抛出异常,像

var mydate =(DateTime)datetimeString 

或 VAR MYD ate = DateTime.Parse(datetimeString)

确实!