C# 如何从ASP.NET核心API中的connection.QueryFirst返回数据
大家好,我正在学习ASP.NET核心 如何将数据从SQLquery返回到json 当前我得到的结果是空的 我的控制器代码片段C# 如何从ASP.NET核心API中的connection.QueryFirst返回数据,c#,asp.net-core-webapi,dapper,asp.net-core-3.1,C#,Asp.net Core Webapi,Dapper,Asp.net Core 3.1,大家好,我正在学习ASP.NET核心 如何将数据从SQLquery返回到json 当前我得到的结果是空的 我的控制器代码片段 [HttpGet] [Route("GetData")] public DataMaster GetData() { using (SqlConnection connection = new SqlConnection(_config.GetConnectionString("EmployeeDBConnection"))
[HttpGet]
[Route("GetData")]
public DataMaster GetData()
{
using (SqlConnection connection = new SqlConnection(_config.GetConnectionString("EmployeeDBConnection")))
{
var param = new DynamicParameters();
// param.Add("@prodtype", prodtype);
return connection.QueryFirst<DataMaster>(" Select producttype,servicetype,servicesubtype,count(*) from master_table group by producttype,servicetype,servicesubtype");
}
}
当我在数据库中执行查询时,我得到以下响应,如何通过API控制器返回此响应
请提供帮助。您似乎正在使用
dapper
&将执行查询并将第一个结果映射到动态列表。
您应该使用:可以使用query方法执行原始SQL查询,并将结果映射到强类型列表。
使用Query
而不是QueryFirst
,并将返回类型更改为IEnumerable
根据注释
您没有获得计数
。我猜您在DataMaster
中有Count
属性,那么您需要在query
中为Count
提供别名,然后它将正确绑定
[HttpGet]
[Route("GetData")]
public IEnumerable<DataMaster> GetData()
{
using (SqlConnection connection = new SqlConnection(_config.GetConnectionString("EmployeeDBConnection")))
{
var param = new DynamicParameters();
// param.Add("@prodtype", prodtype);
return connection.Query<DataMaster>(" Select producttype,servicetype,servicesubtype,count(*) AS Count from master_table group by producttype,servicetype,servicesubtype");
}
}
[HttpGet]
[路由(“获取数据”)]
公共IEnumerable GetData()
{
使用(SqlConnection connection=newsqlconnection(_config.GetConnectionString(“EmployeeDBConnection”))
{
var param=新的动态参数();
//参数Add(“@prodtype”,prodtype);
返回connection.Query(“按producttype、servicetype、servicesubtype从主表组中选择producttype、servicesubtype、count(*)作为计数”);
}
}
预期行为。根据您的图像,第一行全部为空。然后我希望QueryFirst返回所有空值的响应。您想返回什么?第一个非空行?还是所有的结果?可能所有非空结果?@PanagiotisKanavos我想要除空行以外的所有行?我该怎么做呢?你能帮我使用查询
并在查询库中添加产品类型不为NULL的地方
吗?我尝试过帮助,它部分起作用,但我没有得到Count行的响应,你能帮忙吗?我已经更新了答案,如果你想在DataMaster
中的count
属性中绑定count,那么你需要为count
中的count(*)提供alias
,以便query
中的ascount(*)as count
正确绑定。
[HttpGet]
[Route("GetData")]
public IEnumerable<DataMaster> GetData()
{
using (SqlConnection connection = new SqlConnection(_config.GetConnectionString("EmployeeDBConnection")))
{
var param = new DynamicParameters();
// param.Add("@prodtype", prodtype);
return connection.Query<DataMaster>(" Select producttype,servicetype,servicesubtype,count(*) AS Count from master_table group by producttype,servicetype,servicesubtype");
}
}