What .Net data type can call Cannot pass object of type 'to input' System.String '

I have a .Net secret in my hands.

We got the following stack trace

---> System.InvalidCastException: Unable to cast object of type '' to type 'System.String'.
   at System.Data.DataColumn.IsMaxLengthViolated()
   at System.Data.DataTable.EnableConstraints()
   at System.Data.DataTable.EndLoadData()
   at System.Data.Common.DataAdapter.FillFromReader(DataSet dataset, DataTable datatable, String srcTable, DataReaderContainer dataReader, Int32 startRecord, Int32 maxRecords, DataColumn parentChapterColumn, Object parentChapterValue)
   at System.Data.Common.DataAdapter.Fill(DataTable[] dataTables, IDataReader dataReader, Int32 startRecord, Int32 maxRecords)
   at System.Data.DataTable.Load(IDataReader reader, LoadOption loadOption, FillErrorEventHandler errorHandler)

      

The MSSQL database table that caused this error contained only ints and null nvarchar columns of varying length.

The table contained both DBNulls and string values.

No matter what we try, we cannot throw an InvalidCastException where the first type name appears as an empty string '' We have tried every type that we think the db query can return.

  • DBNull
  • INT
  • INT?
  • SqlString

We always get the correct type name in InvalidCastException

We decompiled IsMaxLengthViolated code, suspecting that it built its own InvalidCasetException with a malformed message, but only found a normal personal

if (obj != null && obj != DBNull.Value && ((string) obj).Length > this.MaxLength)

      

This message is seemingly generated by the .Net framework.

Is there any known way to throw such a malformed InvalidCastException that we're missing?

+3


source to share


1 answer


Replace this

if (obj != null && obj != DBNull.Value && ((string) obj).Length > this.MaxLength)

      

from

if (obj != null && obj != DBNull.Value && (Convert.ToString(obj)).Length > this.MaxLength)

      



UPDATE

This question has already been posted at the following link: [InvalidCastException: Unable to overlay object of type "System.DBNull" on type "System.String".]

The answer given in the link above is to do toString with obj, but your best bet is to use Convert.Tostring () to handle null exceptions.

I hope this solves your problem.

-1


source







All Articles