0
        NpgsqlConnection conn = new NpgsqlConnection(Settings.ConnectionString);
        conn.Open();
        NpgsqlCommand command = new NpgsqlCommand("select def_id from datatable where definition_id='00026b41-11e5-4557-823c-376a17e8253f'", conn);
        Int16 _data =  (Int16)command.ExecuteScalar();

This works in SQL, but not in the Code.

I got the System.NullReferenceException. I use npgsql btw. The selected Column has the smallInt format. The other guid. When I reverse selection and try to read the other table and change datatype to guid same error

both works in SQL

Backs
  • 24,430
  • 5
  • 58
  • 85
  • sooooory I have selected the wrong Database....lol. sorry this is my first project and I thought the error was because I had syntax wrong,....but this error really means that it REALLY CAN'T FIND that thing. feel free to delete it..I feel stupid now :( – Tetragrammaton Mar 13 '16 at 07:35

1 Answers1

1

the command.ExecuteScalar(); returns no values and the exceptions is becuase you want to cast it as Int16. You can do it like:

Int16 _data =  (Int16)(command.ExecuteScalar() ?? 0);
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
  • nah it works fine the way I have it....just the wrong Database...but I will look into your command what it does anyway, to learn something new..thx – Tetragrammaton Mar 13 '16 at 07:41
  • 1
    `x = a ?? b` means that `x = a` if `a` is not null otherwise `x = b` . you can also use it like `x = a ?? b ?? c ?? d ...` . `command.ExecuteScalar() ?? 0` means that if `command.ExecuteScalar()` is null return `0` – Ashkan Mobayen Khiabani Mar 13 '16 at 07:47
  • Yeah I remember that from an abstract basic tutorial with simple examples,...but now when you try to program real stuff, you realize how useful it becomes, and how often you will need that.....and I also remember how he said:"You will need that often",....lol..but again with these simple examples in some tuts you don't grasp why, and start to forget it real fast.....now its in my brain. thx – Tetragrammaton Mar 13 '16 at 08:07
  • @Tetragrammaton your welcome – Ashkan Mobayen Khiabani Mar 13 '16 at 08:24