C# 如何从ASP.NET核心API中的connection.QueryFirst返回数据

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"))

大家好,我正在学习ASP.NET核心 如何将数据从SQLquery返回到json 当前我得到的结果是空的

我的控制器代码片段

[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
中的
as
count(*)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");
    }

}