Executing Stored Procedure in Entity Framework Core 2.0

Pradeep H picture Pradeep H · Mar 5, 2018 · Viewed 19.3k times · Source

Have a scenario to execute a stored procedure and read the return value in EF Core, that returns a single value.

I tried with this code, but this does not work. I understand that ExecuteSqlCommand does not work for select and can be used only for update to database.

var test =  context.Database.ExecuteSqlCommand("SPName");

The stored procedure has just a select statement like Select 'somevalue'

Looking for any alternative to get data that stored procedure returns.

Answer

grabhints picture grabhints · Mar 8, 2018
DbCommand cmd = ctx.Database.GetDbConnection().CreateCommand();
cmd.CommandText = "SPName";
cmd.CommandType = CommandType.StoredProcedure;

    if (cmd.Connection.State != ConnectionState.Open)
    {
        cmd.Connection.Open();
    }

return await cmd.ExecuteNonQueryAsync();

Here is a post about that: https://nodogmablog.bryanhogan.net/2016/07/entity-framework-core-and-calling-a-stored-proceduce/#comment-60582