Calling a simple stored procedure in EF core 3.1

那年仲夏 提交于 2020-06-17 01:41:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!