如何在 Web API 和 return 列表中执行存储过程

How to execute a stored procedure in Web API and return a list

我正在学习在 .NET Core Web API 中开发 Web api 服务。现在我试图执行存储过程和 return 一个列表。但是我的代码不显示存储过程执行后的数据。非常感谢任何帮助。

BL

public string VantageEntities { get; private set; }
public List<SalesAndReturns_RPT> GetOrders(string Year, VantageContext _context)
{
    string conn = _context.Database.GetDbConnection().ConnectionString;
    using (SqlConnection sql = new SqlConnection(conn))
    {
        sql.Open();
        using (SqlCommand cmd = new SqlCommand("AllSellout", sql))
        {
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@Year", Year));
            List<SalesAndReturns_RPT> response = null;

            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    //response = Convert.ToDecimal(reader.GetDecimal(0));
                }
            }
            sql.Close();
            return response;
        }
    }
}

控制器

    namespace Vantage.Core.Direct.API.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class PieChartController : ControllerBase
        {
            private readonly VantageContext _context;
            public PieChartController(VantageContext context)
            {
                _context = context;
            }
            [HttpGet]
            public IEnumerable<DAL.Models.SalesAndReturns_RPT> GetOrders(string Year)
            {
                var list = new PieChartMgt().GetOrders(Year, _context);
                return list;
            }
}
}

我的存储过程

ALTER PROCEDURE AllSellout
@Year VARCHAR(6) 
AS
BEGIN
SELECT DISTINCT BusinessArea, sum(NetValue) as sumNetValue
FROM SalesAndReturns_RPT
WHERE  year(Call_ActualStartDate) = @Year
GROUP BY BusinessArea 
ORDER BY sumNetValue DESC
END

SalesAndReturns_RPT.cs

    public partial class SalesAndReturns_RPT
    {
        public int UID { get; set; }
        public string Distributor { get; set; }
        public string Id { get; set; }
        public string DistributorID { get; set; }
        public string Outlet { get; set; }
        public string OutletID { get; set; }
        public string SalesOrgName { get; set; }
        public decimal? NetValue { get; set; }
        public string BusinessArea { get; set; }
}

试试这个

 var response = new  List<SalesAndReturns_RPT>();

   using (var reader = cmd.ExecuteReader())
    {
            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    var sales= new SalesAndReturns_RPT();
                     sales.BusinessArea = Convert.ToDecimal(reader.GetString(0));
                    sales.NetValue  = Convert.ToDecimal(reader.GetDecimal(1));
                
                 response.Add(sales);
                  
                 }
                
            }
     }
     return response;