title: Unable to cast object of type 'System.Int32' to type 'System.String'
body: <p>I'm getting a sporadic 'Unable to cast object of type 'System.Int32' to type 'System.String' Exceptions at .SingleorDefault() in the below code. It works 9/10 times but randomly it throws an exception. I made sure that SettingID that i'm passing has no Null Values and the data in the table always exists for the settingID, and i'm always passing SettingID as Integer. </p>
  
  <p>Any ideas what is wrong with this code.</p>
  
  <p>Here is the Exception Info:</p>
  
  <blockquote>
    <p>System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'.<br>
         at System.Data.SqlClient.SqlBuffer.get_String()<br>
         at Read_CPT_Setting(ObjectMaterializer`1 )<br>
         at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()<br>
         at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)<br>
         at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source)<br>
         at CPT.Service.SettingLinqProvider.GetSettingFromDBById(Int32 SettingId)</p>
  </blockquote>
  
  <p>CODE:</p>
  
  <pre><code>Public Function GetSettingFromDBById(ByVal SettingId As Integer) As ReturnObject(Of Model.ISettingBase) 
  
      Dim retObj As New ReturnObject(Of Model.ISettingBase)
      Dim dbSetting As CPT_Setting
  
      Try
          Dim _cptDB As New CPT.Data.CPTLinqRepository.DB(_connString)
          Using _cptDB
  
               dbSetting = (From s In context.CPT_Settings _
                                    Where s.SettingId = settingId _
                                    Select s).SingleOrDefault
  
              If dbSetting IsNot Nothing Then
                  retObj.ReturnValue = Mapping.Setting.MapDBToModel(dbSetting)
              End If
  
          End Using
      Catch ex As Exception
          retObj.ReturnValue = Nothing
          retObj.AddErrorMessage("Error returning the site: " &amp; ex.Message)
          _log.Error(ex.Message, _userId, ex)
      End Try
  
      If retObj.ReturnValue Is Nothing Then
          retObj.AddErrorMessage("Site Not Found.")
      End If
  
      Return retObj
  End Function
  </code></pre>
  
  <hr>
  
  <p>I've updated the above code with some logging in place after each line. </p>
  
  <pre><code>Public Function GetSettingFromDBById(ByVal SettingId As Integer) As ReturnObject(Of Model.ISettingBase) 
  
      Dim retObj As New ReturnObject(Of Model.ISettingBase)
      Dim dbSetting As CPT_Setting
      Dim SettingsList As New List(Of CPT_Setting)
  
      Dim errStr As String = " ENTER "
  
      Try
          Dim _cptDB As New CPT.Data.CPTLinqRepository.DB(_connString)
          Using _cptDB
              errStr &amp;= " - Inside Context "
              If _cptDB Is Nothing Then
                  errStr &amp;= " - With Context is Nothing "
                  _log.Error("Unusual Object - Unable to create connection object - Object is NOTHING", _userId)
              End If
  
              If System.DBNull.Value.Equals(_cptDB) Then
                  errStr &amp;= " - With Context is NULL "
                  _log.Error("Unusual Object - Unable to create connection object - Object is NULL", _userId)
              End If
  
              errStr &amp;= " - Querying With SettingID = " &amp; SettingId.ToString()
  
              Dim dbSettingTemp = (From s In context.CPT_Settings _
                                Where s.SettingId = settingId _
                                Select s)
  
              If dbSettingTemp Is Nothing Then
                  errStr &amp;= " -- Nothing is returned from DB - Object is NOTHING -- "
                  _log.Error(errStr, _userId)
              End If
              If System.DBNull.Value.Equals(dbSettingTemp) Then
                  errStr &amp;= " -- Nothing is returned from DB - Object is NULL -- "
                  _log.Error(errStr, _userId)
              End If
  
              errStr &amp;= " -- Before SingleOrDefault -- "
              dbSetting = dbSettingTemp.SingleOrDefault
              errStr &amp;= " -- After SingleOrDefault -- "
  
              If dbSetting IsNot Nothing Then
                  If System.DBNull.Value.Equals(dbSetting) Then
                      errStr &amp;= " - NULL OBJECT RETURNED - Before Mapping "
                      _log.Error("Unusual Exception - NULL OBJECT RETURNED " &amp; errStr, _userId)
                  End If
  
                  retObj.ReturnValue = Mapping.Setting.MapDBToModel(dbSetting)
                  errStr &amp;= " - After Mapping With SettingID=" &amp; dbSetting.SettingId.ToString() &amp; " SettingName=" &amp; dbSetting.SettingName.ToString() &amp; " StartDate=" &amp; dbSetting.StartDate.ToShortDateString() &amp; " EndDate=" &amp; dbSetting.EndDate.ToShortDateString()
  
              Else
                  errStr &amp;= " - DBSetting Is Nothing "
                  _log.Error("Unusual Object - No Data Retrieved for SettingID=" &amp; SettingId.ToString() &amp; " " &amp; errStr, _userId)
              End If
  
          End Using
      Catch ex As Exception
          retObj.ReturnValue = Nothing
          retObj.AddErrorMessage("Error returning the site: " &amp; ex.Message)
          _log.Error("Unusual Exception for SettingID=" &amp; SettingId.ToString() &amp; "--" &amp; errStr &amp; "--" &amp; ex.Message, _userId, ex)
      End Try
  
      If retObj.ReturnValue Is Nothing Then
          retObj.AddErrorMessage("Site Not Found.")
          _log.Info("Unusual Object - MRDD Solutions - No Data Retrieved for SettingID=" &amp; SettingId.ToString() &amp; " " &amp; errStr, _userId)
      End If
  
      Return retObj
  End Function
  </code></pre>
  
  <p><strong>Remember: DB has all the rows for all the settingIDs mentioned in below messages.</strong> </p>
  
  <p><strong>Results:</strong> </p>
  
  <p><strong>Scenario 1:</strong> </p>
  
  <p>Unusual Object - No Data Retrieved for SettingID=142176  ENTER  - Inside Context  - Querying With SettingID = 142176 -- Before SingleOrDefault --  -- After SingleOrDefault --  - DBSetting Is Nothing </p>
  
  <p>Unusual Object - MRDD Solutions - No Data Retrieved for SettingID=142176  ENTER  - Inside Context  - Querying With SettingID = 142176 -- Before SingleOrDefault --  -- After SingleOrDefault --  - DBSetting Is Nothing </p>
  
  <p><strong>Scenario 2</strong></p>
  
  <p>Unusual Exception for SettingID=138145-- ENTER  - Inside Context  - Querying With SettingID = 138145 -- Before SingleOrDefault --  -- After SingleOrDefault -- --Specified cast is not valid.</p>
  
  <p>Unusual Object - MRDD Solutions - No Data Retrieved for SettingID=138145  ENTER  - Inside Context  - Querying With SettingID = 138145 -- Before SingleOrDefault --  -- After SingleOrDefault -- </p>
  
  <p><strong>Scenario 3</strong></p>
  
  <p>Unusual Exception for SettingID=164638-- ENTER  - Inside Context  - Querying With SettingID = 164638 -- Before SingleOrDefault -- --Index was outside the bounds of the array.</p>
  
  <p>Unusual Object - MRDD Solutions - No Data Retrieved for SettingID=164638  ENTER  - Inside Context  - Querying With SettingID = 164638 -- Before SingleOrDefault -- </p>