Reputation: 352
After Sql server 2016 we can select data direct as JSON by this statement:
SELECT Top (10) * from Products FOR JSON AUTO
So we no longer need to assign them to objects and convert them to JSON into code. I think we can reduce the complexity of the process and get better performance. I use web API 2 and I want to receive and direct send it to cleint . Is this any new function or method works with SqlCommand to do this? Cloud you help me please?
Upvotes: 3
Views: 12998
Reputation: 22436
This sample shows how to read the JSON from SQL Server using a SqlCommand:
var queryWithForJson = "SELECT ... FOR JSON";
var conn = new SqlConnection("<connection string>");
var cmd = new SqlCommand(queryWithForJson, conn);
conn.Open();
var jsonResult = new StringBuilder();
var reader = cmd.ExecuteReader();
if (!reader.HasRows)
{
jsonResult.Append("[]");
}
else
{
while (reader.Read())
{
jsonResult.Append(reader.GetValue(0).ToString());
}
}
In your ApiController, you can return the string using the ResponseMessage
-method:
public IHttpActionResult Get()
{
var jsonResult = new StringBuilder();
/// get JSON
var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
response.Content = new StringContent(jsonResult.ToString());
return ResponseMessage(response);
}
However, though technically feasible, IMHO there are some disadvantages that you should take into account when going this route:
I assume that it is more efficient to let SQL Server deliver the data in binary format to the frontends that perform the conversion. I doubt that it will be much faster to put this load on the database server - of course this depends on the infrastructure.
Upvotes: 4