Search code examples
.net-corecentos7npgsql

.Net Core Npgsql Return Single Row


I was just wondering if it's possible to return a single row using Npgsql in a .Net Core Script.

I've been doing with the Read Method like bellow

NpgsqlCommand command = new NpgsqlCommand (
    " select col01, col02, col03 from table ",
    dbconnection
);
var result = command.ExecuteReader();
while(result.Read()) {
    var varCol01 = result["col01"];
    var varCol02 = result["col02"];
}

Which seems a bit excessive for a single row because I would have to exit the while manually.


Solution

  • Each time you call NpgsqlDataReader.Read, you're reading an additional row - so your code sample doesn't seem to be a good fit for a single row scenario...

    If you know you're only getting a single row, why not do something along the lines of:

    var reader = command.ExecuteReader();
    reader.Read(); // You can do a Debug.Assert to make sure the result of this is true
    var (col1, col2) = (result["col01"], result["col02"]);