簡體   English   中英

C#實體框架:將EntityObject查詢結果作為JSON返回給ajax

[英]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中返回原始json(字符串)

不知道為什么WCF無法正常將Sample實體返回為JSON。

另一種方法是為SampleSampleSheet編寫映射函數。 基本上我在做什么,但沒有所有手動輸入。

將一個對象投射到另一個對象

我采用第一種方法,因為它不需要我創建任何新類。 只需將實體對象轉換為字符串,然后流式傳輸並返回即可。 缺點是您在JSON中獲得了一堆不必要的值,例如實體鍵對象。 不知道對性能的影響有多大,但似乎並不十分明顯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM