另一种方法:
public T ExecuteScalarFunction<T>(string functionName, List<SqlParameter> parameters, SqlDbType returnSqlType) where T : new()
{
using (var conn = new SqlConnection(CTX.Database.GetDbConnection().ConnectionString))
{
if (conn.State != ConnectionState.Open)
conn.Open();
using (var cmd = new SqlCommand(functionName, conn)) {
cmd.CommandType = CommandType.StoredProcedure;
SqlCommandBuilder.DeriveParameters(cmd);
foreach (var parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
cmd.Parameters.Add("@RETURN_VALUE", returnSqlType).Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
return (T)cmd.Parameters["@RETURN_VALUE"].Value;
}
}
}