After I retrieve my query results I want to return it as a json for the ajax call. I can achieve this, but I'm looking for a cleaner way.
I have a table in my SQL-Server and C# Entity Object Model called Sample. The following snippet fetches a row from the Sample table and returns it back to the service, which is suppose to return it as a json to the client.
public Sample GetRequest(string surveyId)
{
AA.Msat.Sample requestQuery = null;
long surveyIdInteger = Int64.Parse(surveyId);
using (var db = new MSATEntities())
{
requestQuery = (from req in db.Samples
where req.SurveyId == surveyIdInteger
select req).Single();
}
return requestQuery;
}
The ajax calls this Operatrion contract in my service
[OperationContract]
[WebGet(UriTemplate = "request/{surveyId}", ResponseFormat = WebMessageFormat.Json)]
Sample GetRequest(string surveyId);
In chrome I get an error connection refused, but if I return null it is ok.
I can also get it working if I map the query result values manually to a class object containing nothing but the Sample table columns as class members and return that. Shown below:
public SampleSheet GetMsatRequest(string surveyId)
{
Sample requestQuery = null;
long surveyIdInteger = Int64.Parse(surveyId);
using (var db = new MSATEntities())
{
requestQuery = (from req in db.Samples
where req.SurveyId == surveyIdInteger
select req).Single();
}
SampleSheet requestJson = new SampleSheet();
// Copy values
requestJson.SurveyId = requestQuery.SurveyId;
requestJson.PanelId = requestQuery.PanelId.Value;
requestJson.ClientName = requestQuery.ClientName;
requestJson.PanelName = requestQuery.PanelName;
requestJson.AcctMgr = requestQuery.AcctMgr;
return requestJson;
}
}
Where SampleSheet is
public class SampleSheet
{
[DataMember]
public long SurveyId;
[DataMember]
public int PanelId;
[DataMember]
public string ClientName;
[DataMember]
public string PanelName;
[DataMember]
public string AcctMgr;
}
My guess is because Sample cannot be converted into a JSON because Sample contains a lot of other values besides the table values like EntityKeys object. Is there a way to return Sample more easily than what I'm doing? It is quite tedious to map all the values of multiple tables.
EDIT: Here is requestQuery (Sample) serialized into a JSON string to show structure.
{
"$id": "1",
"SurveyId": 728801,
"PanelId": 12,
"ClientName": "hehehe",
"PanelName": "hehehe",
"AcctMgr": "hehhe",
"EntityKey": {
"$id": "2",
"EntitySetName": "Samples",
"EntityContainerName": "MSATEntities",
"EntityKeyValues": [{
"Key": "SurveyId",
"Type": "System.Int64",
"Value": "728801"
}]
}
}