쿼리 결과를 검색 한 후 ajax 호출에 대한 json으로 반환하려고합니다. 나는 이것을 얻을 수 있지만, 나는 더 깨끗한 방법을 찾고있다.C# Entity Framework : Ajax 용 JSON으로 EntityObject 쿼리 결과 반환
SQL - Server 및 C# Entity Object Model에 Sample이라는 테이블이 있습니다. 다음 스 니펫은 Sample 테이블에서 한 행을 가져 와서 서비스로 돌려 보낸다. 이것은 json으로 클라이언트에 리턴한다고 가정한다.
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;
}
아약스는 내가 오류 연결이 거부 얻을 내 서비스 크롬에서
[OperationContract]
[WebGet(UriTemplate = "request/{surveyId}", ResponseFormat = WebMessageFormat.Json)]
Sample GetRequest(string surveyId);
이 Operatrion 계약을 호출하지만 내가 null을 반환한다면 괜찮습니다.
또한 쿼리 결과 값을 클래스 멤버로 Sample 테이블 열을 포함하는 클래스 개체에 수동으로 매핑하고이를 반환하면 작동하도록 할 수 있습니다. 아래 그림 :
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;
}
}
을 SampleSheet는 샘플 EntityKeys 개체와 같은 테이블 값 이외의 다른 값이 많이 포함되어 있기 때문에 샘플은 JSON으로 변환 할 수 없기 때문에
public class SampleSheet
{
[DataMember]
public long SurveyId;
[DataMember]
public int PanelId;
[DataMember]
public string ClientName;
[DataMember]
public string PanelName;
[DataMember]
public string AcctMgr;
}
내 생각이다입니다. 내가하는 일보다 샘플을 더 쉽게 반환 할 수있는 방법이 있습니까? 여러 테이블의 모든 값을 매핑하는 것은 매우 지루합니다.
EDIT : 구조를 표시하기 위해 JSON 문자열로 serialize 된 requestQuery (샘플)입니다.
{
"$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"
}]
}
}
'Sample'? – DavidG
@DavidG Sample의 구조를 보여주기 위해 편집했습니다. 당신이 sql의 테이블을 의미한다면, 그것은 SampleSheet와 같은 컬럼을 가지고 있습니다. – roverred