You need to enable JavaScript to run this app. EF Core 5搭配UOW模式调用存储过程找不到SqlQuery方法该如何实现?
优惠活动
大模型
产品
解决方案
定价
更多

EF Core 5搭配UOW模式调用存储过程找不到SqlQuery方法该如何实现?

问题根因

EF Core 5 中移除了原EF 6 提供的Database.SqlQuery<T>() 方法,你需要改用EF Core原生的原生SQL查询API实现存储过程调用,具体实现方案如下:

前置配置

所有用于接收存储过程返回结果的自定义类,都需要配置为无键实体,有两种配置方式:

  1. 直接在类上添加特性
using Microsoft.EntityFrameworkCore;

[Keyless]
public class 你的存储过程返回类
{
    // 对应存储过程返回的字段属性
    public int Id { get; set; }
    public string Name { get; set; }
}
  1. 在DbContext的OnModelCreating方法中配置
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<你的存储过程返回类>().HasNoKey();
}

代码修改

1. 修正IUnitOfWorkIntegrado接口的GetSP方法签名,增加入参

public interface IUnitOfWorkIntegrado
{
    IRepository<T> Repository<T>() where T : class;
    Task SaveChangesAsync();
    Task BeginTransactionAsync();
    Task RollBackAsync();
    Task CommitAsync();
    // 新增存储过程名称、参数两个入参
    Task<List<T>> GetSP<T>(string spName, params object[] parameters) where T : class;
}

2. 实现GetSP方法

注意要先引用Microsoft.EntityFrameworkCore命名空间,才能调用对应的扩展方法

using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;

public class UnitOfWorkIntegrado : IUnitOfWorkIntegrado
{
    // 假设你已经通过构造函数注入了对应的DbContext实例
    private readonly 你的DbContext类 dbContext;

    // 构造函数注入DbContext代码省略
    
    public async Task<List<T>> GetSP<T>(string spName, params object[] parameters) where T : class
    {
        // 使用FromSqlRaw执行存储过程,返回结果直接映射到无键实体T
        return await dbContext.Set<T>()
            .FromSqlRaw($"EXEC {spName}", parameters)
            .ToListAsync();
    }
}

注意事项

  • 如果需要传入具名参数避免参数顺序错误,可以自己构造SqlParameter实例传入:
    var userIdParam = new SqlParameter("@UserId", 1001);
    var result = await _unitOfWork.GetSP<你的返回类>("SP_GetUserInfo", userIdParam);
    
  • 如果存储过程返回的字段名和实体类的属性名不匹配,需要在无键实体配置时通过HasColumnName手动指定映射关系
  • 如果你要执行无返回值的存储过程,可以直接使用dbContext.Database.ExecuteSqlRaw()方法实现

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 04:06:00