I've a problem of fetching data from database, Because I'm new in c# Language. I thought that the ExecuteReader should retrieve all rows. by the way I can't access the data like full of object. and the reader.GetString(0) it's return to me only the index of array object.
Is any properties from c# to access the row from database?
I'm looking for the answer to solve this problem. I'd appropriated for the helping!
Here is the code I have so far:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Npgsql;
namespace Sample.Controllers
{
public class HomeController : Controller
{
public string Index()
{
var connString = "Host=localhost;Username=postgres;Password=123456;Database=dotnet_core_db";
using (var conn = new NpgsqlConnection(connString))
{
conn.Open();
// Retrieve all rows
using (var cmd = new NpgsqlCommand("SELECT * FROM Persons", conn))
using (var reader = cmd.ExecuteReader())
while (reader.Read())
{
Console.WriteLine(reader.GetString(0));
Console.WriteLine(reader.GetString(1));
Console.WriteLine(reader.GetString(2));
Console.WriteLine(reader.GetString(3));
Console.WriteLine(reader.GetString(4));
ViewData["connString"] = connString;
}
}
return connString;
}
public IActionResult Error()
{
ViewData["RequestId"] = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
return View();
}
}
}
Expectation Result
{
{
id: 92,
name: "foo",
last_name: "bar",
address: "adress Of foo",
city: "city of foo"
},
{
id: 872,
name: "foo1",
last_name: "bar 2",
address: "address of foo1",
city: "city of foo1"
}
}