在Entity Framework Core 2.0中执行存储过程
问题描述:
有一种方案可以执行存储过程并读取EF Core中的返回值,该返回值将返回单个值.
Have a scenario to execute a stored procedure and read the return value in EF Core, that returns a single value.
我尝试使用此代码,但这不起作用.我知道 ExecuteSqlCommand
不适用于select,只能用于更新数据库.
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");
存储过程只有一个select语句,例如 Select'somevalue'
The stored procedure has just a select statement like Select 'somevalue'
寻找任何替代方法来获取存储过程返回的数据.
Looking for any alternative to get data that stored procedure returns.
答
可以使用以下代码解决我的问题.这是基于以下答复中给出的建议.
Able to solve my problem with below code. This is based on suggestions given in below replies.
using (var command = context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = "StoredProcedureName";
command.CommandType = CommandType.StoredProcedure;
context.Database.OpenConnection();
var dataReader = command.ExecuteReader();
if (dataReader.Read())
{
string _test = dataReader.GetString(dataReader.GetOrdinal("ColumnName"));
}
}