When the Address2 column is empty, this line:

string address2 = sqlD8aReader.GetString(ADDRESS2_OFFSET);

...fails with:

  System.Data.SqlTypes.SqlNullValueException was unhandled by user code
  HResult=-2146232015
  Message=Data is Null. This method or property cannot be called on Null values.
  Source=System.Data
  StackTrace:
       at System.Data.SqlClient.SqlBuffer.get_String()
       at System.Data.SqlClient.SqlDataReader.GetString(Int32 i)
       at HandheldServer.Models.SQLServerPOCRepository..ctor() in c:\HandheldServer\HandheldServer\Models\SQLServerPOCRepository.cs:line 58
  InnerException:

How can I safely read strings that might be null? Should it be dealt with in SQL somehow (if so, how?) or should it be dealt with in the reading/C# code?

有帮助吗?

解决方案

I don't know how your data is being populated, but often times when we execute a query where I work, if it's imperative to have empty strings instead of null for certain operations, we'll use ISNULL(column, '') on columns that might possibly return null so our application layer won't need to worry about whether or not the value is null, it will just handle it like a string.

Otherwise, if you want to handle it application side you can use this:

if(!sqlD8aReader.IsDBNull(ADDRESS2_OFFSET))
{
    string address2 = sqlD8aReader.GetString(ADDRESS2_OFFSET);
}

其他提示

A quick one-liner would be

string address2 = sqlD8aReader.IsDBNull(ADDRESS2_OFFSET) 
                  ? null 
                  :sqlD8aReader.GetString(ADDRESS2_OFFSET);

or as an extension method:

public static GetStringOrNull(this IDataRecord dr, int i)
{
    return dr.IsDBNull(i) 
           ? null 
           : dr.GetString(i);
}

and call

string address2 = sqlD8aReader.GetStringOrNull(ADDRESS2_OFFSET);

You can achieve that in your sql query like:

    select * from SomeTable where SomeColumn is not null

This way you wouldn't get that exception. But you should also check if the returned value is null or not like akousmata said.

Handling it from the DB side

1) Make sure Address is not NULL when inserting

INSERT INTO t(Address) VALUES(ISNULL(@Address, ''))

2) Return empty string instead if NULL

SELECT ISNULL(Address, '') as Address FROM t

And you already had good answers from other users sqlReader.IsDBNull

The easiest/Best solution is to make your SQL query print other values instead of null. For example, If I have a column1 where I probably get null values, I would call this query :

SELECT isnull(column1,0) FROM table

which prints 0 instead of null values

Instead of calling this query :

SELECT column1 FROM table 

which prints the null values and throws exceptions when retreiving data with C#.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top