[英]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. 我正在用Npgsql测试新的.net Core RC2,因为我有一个postgres数据库。 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. 我对所有这些都是新手,但是我想做的是从数据库中检索5条记录,然后以Json格式返回。 However, I am only able to output 1 record even though I can see that all 5 records are being returned. 但是,即使看到所有5条记录都已返回,我也只能输出1条记录。 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);
}
}
I'm guessing the value of city returned in the Json object would only contain the last city and state returned from the query. 我猜测Json对象中返回的city的值将仅包含查询返回的最后一个城市和州。 The while loop overwrites the city variable each iteration. while循环在每次迭代时都会覆盖city变量。
Storing each city and state in an array will allow for you to return all 5 cities. 将每个城市和州存储在一个阵列中将使您可以返回所有5个城市。
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. 另一方面,您可以只返回将使用json序列化为javascript数组的数组。
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);
I'd recommend using Entity Framework, and just serialize the Model to json. 我建议使用实体框架,然后将模型序列化为json。 Checkout the Npgsql.EntityFrameworkCore.PostgreSQL -Pre nuget package. 检出Npgsql.EntityFrameworkCore.PostgreSQL -Pre nuget包。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.