在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
/ 内插
和异步
版本。
EF Core 3.x+ provides two raw SQL sets of methods - FromSql
and ExecuteSql
, both with Raw
/ Interpolated
and Async
versions.
前者用于查询。它们返回 IQueryable< T>
,允许进行查询组合,并且由于在枚举结果之前不会执行任何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屋!