在 C# Entity Framework 中阅读 Oracle SYS_REFCURSOR?

Read Oracle SYS_REFCURSOR in C# Entity Framework?

我有一个简单的 C# 控制台应用程序,它的代码是这样的:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oracle.ManagedDataAccess.Client;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            SHRSContext shrsContext = new SHRSContext();

            DbCommand cmd = shrsContext.Database.Connection.CreateCommand();

            cmd.CommandText = "PKG_SHRS.GETLOGINATTEMPT";
            cmd.CommandType = CommandType.StoredProcedure;

            var pinUsername = new OracleParameter("pinUsername", OracleDbType.Varchar2, ParameterDirection.Input);
            pinUsername.Value = "admin";

            var poutLoginAttemptCount = new OracleParameter("poutLoginAttemptCount", OracleDbType.Int16, ParameterDirection.Output);

            cmd.Parameters.Add(pinUsername);
            cmd.Parameters.Add(poutLoginAttemptCount);

            cmd.Connection.Open();
            cmd.ExecuteNonQuery();
            cmd.Connection.Close();

            Console.WriteLine(poutLoginAttemptCount.Value.ToString());
            Console.ReadLine();
        }
    }
}

它使用 entity framework 和 Oracle 11g 作为后端。它在程序包 PKG_SHRS.GETLOGINATTEMPT 中调用一个 Oracle 过程,并且运行良好。

以上代码只提供了一个数字数据类型的输出参数。如果我需要得到一个 table SYS_REFCURSOR 作为输出参数,我需要在给定的代码中更改什么?

我假设 VALIDATELOGIN 过程的输出参数是 poutUserCursor 并且它的类型是 SYS_REFCURSOR。试试这个代码。

SHRSContext shrsContext = new SHRSContext();

DbCommand cmd = shrsContext.Database.Connection.CreateCommand();

cmd.CommandText = "PKG_SHRS.GETLOGINATTEMPT";
cmd.CommandType = CommandType.StoredProcedure;

var pinUsername = new OracleParameter("pinUsername", OracleDbType.Varchar2, ParameterDirection.Input);
pinUsername.Value = "admin";

// Assuming output parameter in the procedure is poutUserCursor
var poutUserCursor = new OracleParameter("poutUserCursor", OracleDbType.RefCursor, ParameterDirection.Output);

cmd.Parameters.Add(pinUsername);
cmd.Parameters.Add(poutUserCursor);

cmd.Connection.Open();

DbDataReader dr = cmd.ExecuteReader();

string column1 = string.Empty;
string column2 = string.Empty;

// Assume this will return one row. If multiple rows return, use while loop
if (dr.Read())
{
    // GetString will return string type. You can change as you need
    column1 = dr.GetString(0);
    column2 = dr.GetString(1);
}

cmd.Connection.Close();