json - List<Object> serialization not working with multiple objects -
i have following classes
[datacontract] public class video { [key] [datamember(isrequired = false)] public int videoid { get; set; } [datamember(isrequired = false)] public int userid { get; set; } [required] [datamember ] public string title { get; set; } [required] [datamember] public virtual ilist<tag> tags { get; set; } } [datacontract] public class tag { [key] [required] [datamember(isrequired = false)] public int? tagid { get; set; } [datamember(isrequired = true)] [required] public string name { get; set; } [ignoredatamember] public virtual ilist<video> videos { get; set; } }
in webapi controller, call this:
var videos = _service.getvideos(); return request.createresponse(httpstatuscode.ok, videos);
which calls this:
public ilist<video> getvideos() { using (var db = createcontext()) { return db.videos.include("tags").tolist(); } }
yet on wire, get:
[{ "$id": "8", "tags": [ { // correct serialization "$id": "9", "tagid": 1, "name": "example", "count": 5 } ], "videoid": 18, "userid": 3, "title": "test video", "thumbnail": "http://i.imgur.com/gv3j2uf.png", "source": "test source" }, { "$id": "19", "tags": [ { // wtf? "$ref": "9" } ], "videoid": 28, "userid": 6, "title": "test video", "thumbnail": "http://i.imgur.com/gv3j2uf.png", "source": "test source" }, { "$id": "20", "tags": [ { // correct again "$id": "21", "tagid": 10, "name": "funny", "count": 2 } ], "videoid": 29, "userid": 6, "title": "test vid", "thumbnail": "https://i.imgur.com/swoqsof.jpg", "source": "test source" }, { "$id": "22", "tags": [ { // incorrect "$ref": "9" }, { "$ref": "21" } ], "videoid": 30, "userid": 6, "title": "test vid", "thumbnail": "https://i.imgur.com/r7lvobx.jpg", "source": "test source" }
for reason - tags
serializing correctly, , not. idea i'm doing wrong?
you have circular references in object graph. cannot json serialized properly, serializer detects condition , automatically makes references ($ref
). when loading object graph using ef there circular references between objects in memory cannot represented correctly in json.
i recommend breaking circular references graph using view model , sending view model on wire instead of directly returning autogenerated ef models.
Comments
Post a Comment