我正在使用Npgsql测试新的.net Core RC2,因为我有一个postgres数据库。我是所有这一切的新手,但我想要做的是从数据库中检索5条记录并以Json格式返回。但是,即使我可以看到所有5条记录都被返回,我也只能输出1条记录。我在这里错过了什么..
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);
}
}
答案 0 :(得分:2)
我猜测在Json对象中返回的city的值只包含查询返回的最后一个城市和州。 while循环每次迭代都会覆盖城市变量。
将每个城市和州存储在一个数组中将允许您返回所有5个城市。
代码更新
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);
数组返回
另一方面,您可以使用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);
答案 1 :(得分:0)
我建议使用Entity Framework,并将Model序列化为json。查看Npgsql.EntityFrameworkCore.PostgreSQL -Pre nuget包。