You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core后端执行原生SQL返回数据至Angular的技术疑问

原生SQL查询在.NET Core后端的实现方案

针对你的问题,直接给结论:完全不需要新增数据表和模型,你的需求只需要保留服务层逻辑和控制器就足够了,理由和优化方案如下:

核心原因

  1. 不需要新增数据表:你是对已存在的Employee表执行只读查询,目的只是获取数值结果展示给前端,根本不需要创建新表来存储数据。
  2. 不需要实体模型:如果只是返回数值类型结果(比如单个统计值、数值列表),直接用.NET的基础类型(int、decimal、List<int>等)或者匿名类型就可以搞定,没必要定义EF Core的实体模型——毕竟你不需要将这些查询结果映射到数据库实体,只是临时读取展示而已。

优化你的初始代码

你的原始代码用了ExecuteReader,这没问题,但针对数值类型的查询可以更高效。举两个常见场景的优化示例:

场景1:获取单个数值(比如员工总数)

public async Task<int> GetEmployeeTotalCount()
{
    using var command = _db.Database.GetDbConnection().CreateCommand();
    command.CommandText = "SELECT COUNT(*) FROM ***.[dbo].[Employee]";

    // 确保连接状态正确,用异步方法更贴合.NET Core的异步编程模型
    if (command.Connection.State != System.Data.ConnectionState.Open)
        await command.Connection.OpenAsync();

    // ExecuteScalar专门用于获取单个结果值,比ExecuteReader更轻量
    var result = await command.ExecuteScalarAsync();
    return Convert.ToInt32(result);
}

场景2:获取多个数值(比如所有员工的ID列表)

public async Task<List<int>> GetAllEmployeeIds()
{
    var employeeIds = new List<int>();

    using var command = _db.Database.GetDbConnection().CreateCommand();
    command.CommandText = "SELECT EmployeeId FROM ***.[dbo].[Employee]";

    if (command.Connection.State != System.Data.ConnectionState.Open)
        await command.Connection.OpenAsync();

    using var reader = await command.ExecuteReaderAsync();
    while (await reader.ReadAsync())
    {
        employeeIds.Add(reader.GetInt32(0));
    }

    return employeeIds;
}

控制器层示例

把服务层的查询结果返回给Angular前端,控制器只需要简单封装:

[ApiController]
[Route("api/employee")]
public class EmployeeController : ControllerBase
{
    private readonly AppDbContext _db;

    public EmployeeController(AppDbContext db)
    {
        _db = db;
    }

    [HttpGet("total-count")]
    public async Task<IActionResult> GetTotalEmployeeCount()
    {
        var count = await GetEmployeeTotalCount();
        return Ok(count);
    }

    [HttpGet("all-ids")]
    public async Task<IActionResult> GetEmployeeIdList()
    {
        var ids = await GetAllEmployeeIds();
        return Ok(ids);
    }
}

总结

你只需要:

  • 在服务层(推荐解耦,不要直接把查询逻辑写在控制器)实现原生SQL的读取逻辑
  • 控制器负责将查询结果以JSON格式返回给Angular前端
  • 全程不需要新增任何数据表,也不需要定义EF实体模型

内容的提问来源于stack exchange,提问作者zarzou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:53:09