简体   繁体   English

C#实体框架:将EntityObject查询结果作为JSON返回给ajax

[英]C# Entity Framework: Returning EntityObject query result back as JSON for ajax

After I retrieve my query results I want to return it as a json for the ajax call. 检索查询结果后,我想将其作为ajax调用的json返回。 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. 我的SQL Server和C#实体对象模型中有一个名为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. 以下代码段从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;
    }

The ajax calls this Operatrion contract in my service Ajax在我的服务中称此Operatrion合同

    [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. 在chrome中,我收到一个错误的连接被拒绝,但是如果我返回null,就可以了。

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. 如果我将查询结果值手动映射到一个仅包含Sample表列作为类成员的类对象,并将其返回,我也可以使它工作。 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 SampleSheet在哪里

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. 我的猜测是因为Sample无法转换为JSON,因为Sample除了表值(例如EntityKeys对象)外还包含许多其他值。 Is there a way to return Sample more easily than what I'm doing? 有没有比我正在做的事更容易返回Sample的方法? 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. 编辑:这是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"
        }]
    }
}

So I found a couple ways to do this. 因此,我找到了几种方法来做到这一点。

One is converting the Sample Entity to a JSON string then a stream: 一种是将Sample Entity转换为JSON字符串,然后转换为流:

Returning raw json (string) in wcf 在wcf中返回原始json(字符串)

Don't get why WCF can't return the Sample entity as JSON normally. 不知道为什么WCF无法正常将Sample实体返回为JSON。

Another way is to write a mapping function for Sample and SampleSheet . 另一种方法是为SampleSampleSheet编写映射函数。 Basically what I"m doing but without all the manual typing. 基本上我在做什么,但没有所有手动输入。

Cast one object to another 将一个对象投射到另一个对象

I went with the first method as it doesn't require me to make any new classes. 我采用第一种方法,因为它不需要我创建任何新类。 Just convert the entity object to a string then stream and return. 只需将实体对象转换为字符串,然后流式传输并返回即可。 The downside is you get a bunch of unnecessary values in the JSON such as entity key objects. 缺点是您在JSON中获得了一堆不必要的值,例如实体键对象。 Not sure how significant the performance hit is, but doesn't seem very noticeable. 不知道对性能的影响有多大,但似乎并不十分明显。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM