EF Core 3.1调用返回JSON的存储过程报错:Sequence contains no elements
解决方案
问题原因
EF Core 的 FromSqlRaw 是为映射表格式查询结果到实体类设计的,但你的存储过程返回的是单个JSON字符串,并非结构化的行集数据,DbSet<Sp> 无法匹配这种非表格式的返回值,因此抛出"Sequence has no elements"错误。
可行实现方案
直接通过数据库连接执行存储过程,读取返回的JSON字符串后反序列化为目标实体,具体步骤如下:
1. 修正实体类属性匹配
确保实体类属性名与JSON结构对应:
public class Sp { public List<Video> X { get; set; } public class Video { public int id { get; set; } public string title { get; set; } } }
2. 调整EF Core调用逻辑
绕过DbSet.FromSqlRaw,直接使用数据库连接执行存储过程:
using Microsoft.EntityFrameworkCore; using System.Text.Json; public async Task<ActionResult<Sp>> X() { // 获取数据库连接 using var connection = _context.Database.GetDbConnection(); await connection.OpenAsync(); // 配置存储过程命令 using var command = connection.CreateCommand(); command.CommandText = "dbo.GetVideo"; command.CommandType = System.Data.CommandType.StoredProcedure; // 读取返回的JSON字符串 var jsonResult = await command.ExecuteScalarAsync() as string; // 反序列化为目标实体 var result = JsonSerializer.Deserialize<Sp>(jsonResult, new JsonSerializerOptions { PropertyNameCaseInsensitive = true // 忽略大小写匹配属性 }); return Ok(result); }
关键注意点
- 不要用
DbSet.FromSqlRaw处理非行集类型的返回结果,这类API仅适用于映射表结构数据。 - 使用
ExecuteScalarAsync读取单一JSON字符串,因为存储过程返回的是单个值(完整JSON内容)。 - 反序列化时开启
PropertyNameCaseInsensitive,确保JSON中的x能正确匹配实体类的X属性。
内容的提问来源于stack exchange,提问作者Jeb50
相关产品推荐
相关产品推荐

