How to resolve an IndexOutOfRangeException on bit value?

送分小仙女□ 提交于 2020-01-07 00:04:07

问题


I'm reading back a bit value from an SQL table, and casting as a boolean value to map to a boolean model value.

But when I read back the IsPDLChecked bit field and initialise as false, I get an index out of range exception.

I looked up the definition of the exception and I'm not sure why the value is out of range due to it being init with a false value, ie, 0. So it's not a negative range value.

Question:

Why am I getting an IndexOutOfRange exception although the bit value being read back is cast to bool and init to false?

Code:

Model -

public partial class EmailContact
{
    public int ContactID { get; set; }
    public bool IsPDLChecked { get; set; }
    public string ContactDisplayName { get; set; }
    public string ContactEmailAddress { get; set; }   

}

Data reader snippet -

while (dataReader.Read())
{
    statusList.Add(new EmailContact(dataReader["IsPDLChecked"] as bool? ?? false,dataReader["ContactDisplayName"].ToString(), dataReader["ContactEmailAddress"].ToString()));
}

Error detail:

System.IndexOutOfRangeException was caught
HResult=-2146233080
Message=IsPDLChecked
Source=System.Data
StackTrace:

at System.Data.ProviderBase.FieldNameLookup.GetOrdinal(String fieldName)
at System.Data.SqlClient.SqlDataReader.GetOrdinal(String name)
at System.Data.SqlClient.SqlDataReader.get_Item(String name)

DB Schema: (I did notice the "CHARACTER_MAX_LENGTH" column is set to null on this):

DB values: (IsPDLChecked has a value)


回答1:


The documentation says that the IndexOutOfRangeException you're getting is thrown when "the name specified is not a valid column name".

The first thing you should do is to make sure the columns name in C# match those in the table (or in the query if they are redefined):

SELECT ContactDisplayName, ContactEmailAddress, IsPDLChecked FROM table

or

SELECT * FROM table

will return column names that will be the same as they are in the table and your reader should be fine as it is right now.

But if your query looks like this:

SELECT ContractDisplayName as Name,
       ContactEmailAddress as Email,
       IsPDLChecked as Checked
  FROM table

you will need to read the result like this in C#:

dataReader["Name"]
dataReader["Email"]
dataReader["Checked"]


来源:https://stackoverflow.com/questions/37211894/how-to-resolve-an-indexoutofrangeexception-on-bit-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!