我有一个返回refcursor的过程
TYPE TEST_LIST IS REF CURSOR;
Procedure TestProcedure (Id IN NUMBER, Result OUT TEST_LIST)
IS
BEGIN
OPEN Result
FOR
SELECT distinct o.paramNumber, o.paramVArchar
FROM testBD o
WHERE o.id = Id;
CLOSE Result;
END TestProcedure;
然后是DataTable的类。
public class TestList
{
public long ParamNumber { get; set; }
public string ParamVarchar { get; set; }
}
执行该过程的方法,然后将DataTable导入列表,将其转换为json-string:
public string GetResult(long id)
{
using (var connection = new OracleConnection())
{
connection.ConnectionString = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
using (var command = connection.CreateCommand())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = $"{PackageName}.TestProcedure";
parameter.Add("Id", OracleDbType.Long).Value = Id;
command.Parameters.Add("Result", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
OracleDataAdapter da = new OracleDataAdapter(command);
////creating and filling datatable
DataTable dt = new DataTable();
connection.Open();
da.Fill(dt);
connection.Close();
//creating a serializer
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
//creating a dictionary list
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
//filling list with datatable rows
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
//returning a serialized string out of list
return serializer.Serialize(rows);
}
}
}
最后我有一个带有get请求的控制器
public string Get(long id)
{
return TestClass.GetResult(id);
}
我从中得到了一些错误。我需要从ref光标中获取json中的字符串或列表。也许有一种更简单的方法可以做到这一点?或者我在这里做错了什么?
答案 0 :(得分:0)
将参数作为参数传出时,请勿关闭存储过程中的光标。它立即关闭,WebAPI无法处理。您的using语句可确保在处理连接时光标关闭,因为光标在没有连接的情况下无法生存。
答案 1 :(得分:0)
实现这一目标的方法是
Result = from row in dt.AsEnumerable()
select new
{
param1 = (string)row["PARAMNUMBER"],
param2 = (string)row["PARAMVARCHAR"]
};
string json = JsonConvert.SerializeObject(Result, Formatting.None);