在 EF core 3.1 中调用一个简单的存储过程 [英] Calling a simple stored procedure in EF core 3.1
问题描述
我有一个非常简单的存储过程:
I have a very simple stored procedure:
CREATE PROCEDURE [dbo].[ClearIterations]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
delete from iterations
END
GO
当从 EF 调用它时,它不会被调用.我没有收到任何错误:
When calling it from EF it is not called. I get no errors:
public void ClearIterations()
{
this.Iterations.FromSqlRaw("ClearIterations").IgnoreQueryFilters();
}
有什么指点吗?我在此处的另一个线程上找到了上面的示例,上面的代码就是答案.我必须将其称为 this.Iterations 以调用 SP,这似乎有点奇怪.
Any pointers? I found the sample above on another thread in here that where the code above is the answer. It seems kind of strange I have to call this this.Iterations to call a SP.
推荐答案
EF Core 3.x+ 提供了两组原始 SQL 方法 - FromSql
和 ExecuteSql
,两者都带有Raw
/Interpolated
和 Async
版本.
EF Core 3.x+ provides two raw SQL sets of methods - FromSql
and ExecuteSql
, both with Raw
/ Interpolated
and Async
versions.
前者用于查询.它们返回 IQueryable
,允许查询组合,因为在枚举结果之前不会执行任何 LINQ 查询.
The former are used for querying. They return IQueryable<T>
, allow query composition and as any LINQ query are not executed until the result is enumerated.
而后者用于立即执行任意 SQL(DDL、DML、批处理等).它们相当于 ADO.NET ExecuteNonQuery
的 EF Core,并返回受影响的记录.输出(或输入/输出)原始值参数可用于获取结果.
While the later is used to immediately execute arbitrary SQL (DDL, DML, batch etc.). They are EF Core equivalent of ADO.NET ExecuteNonQuery
and return the records affected. Output (or input/output) primitive value parameters can be used to obtain the results.
很快,ExecuteSql
方法就是您要寻找的.以您的示例为例,ExecuteSqlRaw,例如(假设这是您的 DbContext
派生类中的方法):
Shortly, ExecuteSql
methods are what you are seeking for. With your example, ExecuteSqlRaw, e.g. (assuming this is method in your DbContext
derived class):
public void ClearIterations()
{
this.Database.ExecuteSqlRaw("ClearIterations");
}
这篇关于在 EF core 3.1 中调用一个简单的存储过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!