We help IT Professionals succeed at work.

Data is Null. This method or property cannot be called on Null values.

Hi there;

I am trying to convert an SQL DataReader to an Entity:

public User ConverterForDataReaderToEntity(SqlDataReader reader) {

User user = new User
                    {
                       
                        ID = reader.GetString(0),                        
                        Name = reader.IsDBNull(1) ? null : reader.GetString(1),
                       //this is also fails Name = reader.IsDBNull(1) ? string.Empty : reader.GetString(1),
                        Department = reader.IsDBNull(2) ? null : reader.GetString(2),
                        Hobby = reader.GetString(3),
                    };
return user;
}
Yet, I fail with error; "Data is Null. This method or property cannot be called on Null values."

All of the fields are nvarchar and ID is PK
In Name and Department columns, null values are allowed.

How to fix this?

Kind regards.
Comment
Watch Question

Jens FiedererTest Developer/Validator

Commented:
Have you fetched the first record yet?
SAMIR BHOGAYTATeam Lead
CERTIFIED EXPERT

Commented:
Hello,

You can check the values are null or not with IsDBNull.
CERTIFIED EXPERT
Commented:
Thanks for the interest. Here is the solution that worked like a charm;

http://www.c-sharpcorner.com/Forums/Thread/67165/error-message-data-is-null-this-method-or-property-can.aspx
CERTIFIED EXPERT

Author

Commented:
Thanks for the interest. Here is the solution that worked like a charm;

http://www.c-sharpcorner.com/Forums/Thread/67165/error-message-data-is-null-this-method-or-property-can.aspx

Commented:
Sure you don't crash on hobby?
CERTIFIED EXPERT

Author

Commented:
>>Sure you don't crash on hobby?
Sorry?