How to call a stored procedure in EF Core 3.0 via FromSqlRaw(转载)
问:
I recently migrated from EF Core 2.2 to EF Core 3.0.
Unfortunately, I haven't found a way to call a stored procedure that returns an entity.
In EF Core 2.0 it was possible:
var spParams = new object[] { "bla", "xx" }; var createdPath = ModelContext.Paths.FromSql("AddNodeWithPathProc @p0, @p1", spParams).Single();
In EF Core 3.0 the method FromSQL is replaced with FromSqlRaw. However, I didn't manage to successfully call a stored procedure and then process the value. This is useful when the stored procedure inserts data into the database.
So in EF Core 3.0, I use this code:
var createdPath = ModelContext.Paths.FromSqlRaw("AddNodeWithPathProc @p0, @p1", spParams).Single();
but it will throw an exception, because the generated SQL is invalid and looks something like this:
exec sp_executesql N'SELECT TOP(2) [p].[PathId], [p].[Level], [p].[NodeId], [p].[NodePath], [p].[NodePathString] FROM ( @sql @p0, @p1 ) AS [p]',N'@p0 nvarchar(4000),@p1 nvarchar(4000), @sql nvarchar(100)',@p0=N'1a',@p1=N'', @sql=N'AddNodeWithPathProc'
I tried quite a few variations, but without success.
I'm starting to think that it is not possible to run stored procedures with ModelContext.[IQueryable].FromSqlRaw. In my opinion this kind defeats one of the major reasons for FromSqlRaw because, for normal select statements, LINQ is normally good enough.
Does anyone know how to use stored procedures in combination with FromSqlRaw in EF Core 3.0? Any help is greatly appreciated.
Thanks in advance
PS: I know you can execute a stored procedure with this.Database.ExecuteSqlRaw(SQL, parameters). However, that way it is not possible retrieve any entities that the stored procedure queries.
答:
Try .ToList() instead of .Single(). .Single() is generating the "TOP(2)" wrapper.
var createdPath = ModelContext.Paths.FromSqlRaw("AddNodeWithPathProc {0}, {1}", nodeTitle, parentPathString).ToList();
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
2018-11-06 允许跨域资源共享(CORS)携带 Cookie (转载)