问题
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
When calling it from EF it is not called. I get no errors:
public void ClearIterations()
{
this.Iterations.FromSqlRaw("ClearIterations").IgnoreQueryFilters();
}
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.
回答1:
EF Core 3.x+ provides two raw SQL sets of methods - FromSql
and ExecuteSql
, both with Raw
/ Interpolated
and Async
versions.
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.
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.
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");
}
来源:https://stackoverflow.com/questions/61350862/calling-a-simple-stored-procedure-in-ef-core-3-1