我们创建了用于查询Oracle DB的Web API,并以JSON格式返回结果。 Web API接受两个输入参数的数组,一个是需要选择的列名数组,另一个是WHERE子句中使用的ID数组。在我们的例子中,SQL语句使用各种表和各种连接非常复杂,因此我只是简单地选择此处而不是庞大的复杂SQL语句。
控制器如下所示
namespace PSData.Controllers
{
public class PDController : ApiController
{
public HttpResponseMessage Getdetails([FromUri] string[] id, [FromUri] string[] Column)
{
List<OracleParameter> prms = new List<OracleParameter>();
List<string> selectionStrings = new List<string>();
string connStr = ConfigurationManager.ConnectionStrings["PDConnection"].ConnectionString;
using (OracleConnection dbconn = new OracleConnection(connStr))
{
var inconditions = id.Distinct().ToArray();
var srtcon = string.Join(",", inconditions);
DataSet userDataset = new DataSet();
var colDict = new Dictionary<string, string>()
{
{"CATEGORY", "STPR_STD_ANML.DESCR"},
{"SESSION_NUMBER", "STPR_STD_ANML.SESSION_NUM"},
{"SESSION_START_DATE","Trunc(STPR_STD_ANML.START_DATE)"}
};
foreach (string col in Column)
{
string selector = colDict[col];
selectionStrings.Add(string.Format("{0} AS {1}", selector, col));
}
string selectString = string.Join(",", selectionStrings);
var strQuery = string.Format(@"SELECT DISTINCT {0}
FROM
STPR_STD_ANML WHERE
STPR_STUDY.STPR_STD_ANML(", selectString);
StringBuilder sb = new StringBuilder(strQuery);
for (int x = 0; x < inconditions.Length; x++)
{
sb.Append(":p" + x + ",");
OracleParameter p = new OracleParameter(":p" + x, OracleDbType.NVarchar2);
p.Value = inconditions[x];
prms.Add(p);
}
if (sb.Length > 0) sb.Length--;
strQuery = sb.ToString() + ")";
using (OracleCommand selectCommand = new OracleCommand(strQuery, dbconn))
{
selectCommand.Parameters.AddRange(prms.ToArray());
using (OracleDataAdapter adapter = new OracleDataAdapter(selectCommand))
{
DataTable selectResults = new DataTable();
adapter.Fill(selectResults);
var returnObject = new { data = selectResults };
var response = Request.CreateResponse(HttpStatusCode.OK, returnObject, MediaTypeHeaderValue.Parse("application/json"));
ContentDispositionHeaderValue contentDisposition = null;
if (ContentDispositionHeaderValue.TryParse("inline; filename=PSData.json", out contentDisposition))
{
response.Content.Headers.ContentDisposition = contentDisposition;
}
return response;
}
}}}}
因为我们遇到问题序列化响应正文并得到错误
"The 'ObjectContent1' type failed to serialize the response body for content type 'application/json; charset=utf-8'."
所以我试图将模型和数据库上下文嵌入到应用程序中。我试过都喜欢
namespace PSData.Models
{
public class StudyDataModel
{
[Key]
public string CATEGORY { get; set; }
public int SESSION_NUMBER { get; set; }
public DateTime SESSION_START_DATE { get; set; }
}}
数据库上下文
namespace PSData.Models
{
public class StudyDataContext:DbContext
{
public DbSet<StudyDataModel> details { get; set; }
}}
我不确定如何在Controller中使用此模型和DBContext,而不是直接处理数据库。这是我的第一个.NET应用程序,有点卡住了。非常感谢任何帮助。