C # MVC4 Web API - JSON result should return objects instead of $ ref for an object

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

In JSON, I return, there are cases when the same child node is present for several parent nodes. In these cases, the first occurrence of the node child is fully displayed with all its members. Any subsequent occurrence appears as $ ref for the first entry. Instead, I would like to see the complete object each time it appears in the returned JSON.

For example, instead of seeing:

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

I would like:

  [{ "$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 JSON. Is there any way?

Thanks!

+7
source share
1 answer

A simple way is to edit the code of the generated entities. For each of the entity classes, the attribute [DataContract(IsReference=true)] will be 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.

+1
source

All Articles