Search code examples
c#asp.net-corenpgsql

C# .net core how can I retrieve all rows using npgsql


I am testing out the new .net Core RC2 with Npgsql because I have a postgres database. I am new to all of this but what I am trying to do is to retrieve 5 records out of a database and return it back in Json format. However, I am only able to output 1 record even though I can see that all 5 records are being returned. What am I missing here..

public JsonResult About()
{
    using (NpgsqlConnection conn = new NpgsqlConnection("myconnection"))
    {
        conn.Open();

        string city="";
        string state= "";
        NpgsqlCommand cmd = new NpgsqlCommand("select city,state from streams limit 5", conn);

        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                city = reader.GetString(reader.GetOrdinal("city"));
                state = reader.GetString(reader.GetOrdinal("state"));
            }
        }
        return Json(city);
    }
}

Solution

  • I'm guessing the value of city returned in the Json object would only contain the last city and state returned from the query. The while loop overwrites the city variable each iteration.

    Storing each city and state in an array will allow for you to return all 5 cities.

    Code Update

    string city="";
    string state= "";
    NpgsqlCommand cmd = new NpgsqlCommand("select city,state from streams limit 5", conn);
    
    var cities = new string[5]();
    using (var reader = cmd.ExecuteReader())
    {
        var i = 0;
        while (reader.Read())
        {
            city = reader.GetString(reader.GetOrdinal("city"));
            state = reader.GetString(reader.GetOrdinal("state"));
    
            cities[i++] = city;
        }
    }
    
    // Aggregate into one string
    var citiesString = String.Join(", ", cities);
    
    return Json(citiesString);
    

    Array return

    On the other hand you can just return the array which will serialize into a javascript array using json.

    string city="";
    string state= "";
    NpgsqlCommand cmd = new NpgsqlCommand("select city,state from streams limit 5", conn);
    
    var cities = new string[5]();
    using (var reader = cmd.ExecuteReader())
    {
        var i = 0;
        while (reader.Read())
        {
            city = reader.GetString(reader.GetOrdinal("city"));
            state = reader.GetString(reader.GetOrdinal("state"));
    
            cities[i++] = city;
        }
    }
    return Json(cities);