[英]C# Entity Framework: Returning EntityObject query result back as JSON for ajax
检索查询结果后,我想将其作为ajax调用的json返回。 我可以实现,但是我正在寻找一种更清洁的方法。
我的SQL Server和C#实体对象模型中有一个名为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;
}
Ajax在我的服务中称此Operatrion合同
[OperationContract]
[WebGet(UriTemplate = "request/{surveyId}", ResponseFormat = WebMessageFormat.Json)]
Sample GetRequest(string surveyId);
在chrome中,我收到一个错误的连接被拒绝,但是如果我返回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在哪里
public class SampleSheet
{
[DataMember]
public long SurveyId;
[DataMember]
public int PanelId;
[DataMember]
public string ClientName;
[DataMember]
public string PanelName;
[DataMember]
public string AcctMgr;
}
我的猜测是因为Sample无法转换为JSON,因为Sample除了表值(例如EntityKeys对象)外还包含许多其他值。 有没有比我正在做的事更容易返回Sample的方法? 映射多个表的所有值非常繁琐。
编辑:这是requestQuery(Sample)序列化为JSON字符串以显示结构。
{
"$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
Entity转换为JSON字符串,然后转换为流:
不知道为什么WCF无法正常将Sample
实体返回为JSON。
另一种方法是为Sample
和SampleSheet
编写映射函数。 基本上我在做什么,但没有所有手动输入。
我采用第一种方法,因为它不需要我创建任何新类。 只需将实体对象转换为字符串,然后流式传输并返回即可。 缺点是您在JSON中获得了一堆不必要的值,例如实体键对象。 不知道对性能的影响有多大,但似乎并不十分明显。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.