C# MVC4 Web API - Resulting JSON should return objects instead of $ref to object

[亡魂溺海] 提交于 2021-02-18 11:10:05

问题


I have an ASP.NET MVC 4 Web API app using EntityFramework for ORM.

In the JSON I return, there are some cases where the same child node is present for multiple parent nodes. In these cases, the first occurrence of the child node is fully visible with all it's members. Any subsequent occurrence shows up as a $ref to the first occurrence. I'd like instead to see the full object everytime it shows up in the JSON returned.

For example, instead of seeing:

    [{
    "$id": "1",
    "userId": 1,
    "Badge": {
        "$id": "2",
        "badgeId": 1,
        "badgeName": "Gold"
        }
    }, {
    "$id": "3",
    "userId": 2,
    "Badge": {
        "$ref": "2"
        }
    }]

i'd like to see:

    [{
    "$id": "1",
    "userId": 1,
    "Badge": {
        "$id": "2",
        "badgeId": 1,
        "badgeName": "Gold"
        }
    }, {
    "$id": "3",
    "userId": 2,
    "Badge": {
        "$id": "4",
        "badgeId": 1,
        "badgeName": "Gold"
        }
    }]

Basically I want to get rid of any "$ref" in the JSON. Is there a way?

Thanks!


回答1:


An easy way is to edit the generated entity classes code. For each of the entity classes, there will be a [DataContract(IsReference=true)] attribute assigned.

Something like the following:

[EdmEntityTypeAttribute(NamespaceName="YourNamespace", Name="YourEntity")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class YourEntity : EntityObject
{

Change it to IsReference=false. That should do the trick.




回答2:


In my case, I'm using the Entity model, I simply set an entity key for a unique field in my .edmx diagram table.



来源:https://stackoverflow.com/questions/11237540/c-sharp-mvc4-web-api-resulting-json-should-return-objects-instead-of-ref-to-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!