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

EF Core 8如何无需创建表获取含关联查询的存储过程结果?

在ASP.NET Core 8 API中无需DbSet调用存储过程获取结果

你可以通过以下两种方式实现,无需创建对应DbSet和数据库表:

方法一:使用EF Core的SqlQueryAsync(推荐,EF Core 7+支持)

先创建一个与存储过程返回字段结构匹配的普通类(无需添加到DbContext的DbSet集合,也无需配置实体映射):

public class PollResult
{
    // 属性名需与存储过程返回的字段名一致,或用[Column]指定映射
    public int Id { get; set; }
    public string PollTitle { get; set; }
    public DateTime CreateTime { get; set; }
    // 根据存储过程返回的字段补充其他属性
}

直接通过Database.SqlQueryAsync调用存储过程并映射到该类:

// 无参数调用
var pollResults = await _dbContext.Database.SqlQueryAsync<PollResult>("EXEC SpGetPoll");
var pollList = pollResults.ToList();

// 带参数调用示例
var param = new SqlParameter("@PollId", 1);
var pollResultsWithParam = await _dbContext.Database.SqlQueryAsync<PollResult>(
    "EXEC SpGetPollById @PollId", param);

方法二:使用ADO.NET原生方式

如果需要更底层的控制,可以直接通过数据库连接执行存储过程:

using var connection = _dbContext.Database.GetDbConnection();
await connection.OpenAsync();

using var command = connection.CreateCommand();
command.CommandText = "SpGetPoll";
command.CommandType = System.Data.CommandType.StoredProcedure;

// 添加参数(如果需要)
// command.Parameters.Add(new SqlParameter("@ParamName", paramValue));

using var reader = await command.ExecuteReaderAsync();
var pollList = new List<PollResult>();

while (await reader.ReadAsync())
{
    var poll = new PollResult
    {
        Id = reader.GetInt32(reader.GetOrdinal("Id")),
        PollTitle = reader.GetString(reader.GetOrdinal("PollTitle")),
        CreateTime = reader.GetDateTime(reader.GetOrdinal("CreateTime"))
        // 逐个映射存储过程返回的字段
    };
    pollList.Add(poll);
}

注意事项

  • 自定义类的属性需与存储过程返回的字段名匹配,大小写敏感(取决于数据库配置),也可通过[Column("字段名")]特性显式指定映射关系。
  • 存储过程如果有输出参数或返回值,可通过对应方式获取(ADO.NET方式更灵活处理这类场景)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 01:20:04