c# - Seralization issue in WebApi 2.0 -
i developing rest api using ef 6.0 code first, automapper , webapi 2.0.
i struggling serializing data, or more specific; selecting should serialized when responding request.
lets creating app a football league has following classes:
public class player { public string name { get; set; } public virtual icollection<team> teams { get; set; } // example } public class team { public string name { get; set; } public virtual icollection<team> players { get; set; } public virtual icollection<footballgame> games { get; set; } } public class footballgame { public team team1 { get; set; } public team team2 { get; set; } public datetime datetime { get; set; } } i have api controller named playerscontroller, , normal method url/api/players/id should return player.
however, due lazyloading, serialization , many-to-many relations every object related player returned:
{ "$id": "1", "id": 1, "name": "jon jones", "teams": [ { "$id": "2", "id": 1, "name": "liverpool", "players": [ { "$id": "3", "id": 2, "name": "james white", "teams": [ { "$ref": "2" }, { "$id": "4", "id": 2, "name": "man utd", "players": [ { "$ref": "3" }, { "$id": "5", "id": 3, "name": "john snow", "teams": [ { "$ref": "2" }, { "$ref": "4" } ] }, { "$ref": "1" } ], "games": [ { "$id": "6", "id": 1, "team1": { "$ref": "2" }, "team2": { "$ref": "4" }, "datetime": "2014-08-18t23:20:01.7797942+02:00" }, { "$id": "7", "id": 2, "team1": { "$id": "8", "id": 3, "name": "man city", "players": [ { "$ref": "1" }, { "$ref": "3" }, { "$id": "9", "id": 4, "name": "elton john", "teams": [ { "$ref": "2" }, { "$ref": "8" } ] } ], "games": [ { "$ref": "7" }, { "$id": "10", "id": 5, "team1": { "$ref": "2" }, "team2": { "$ref": "8" }, "datetime": "2014-08-18t23:20:01.7807943+02:00" } ] }, "team2": { "$ref": "4" }, "datetime": "2014-08-18t23:20:01.7807943+02:00" } ] }, { "$ref": "8" } ] }, { "$ref": "5" }, { "$ref": "9" } ], "games": [ { "$ref": "6" }, { "$ref": "10" } ] }, { "$ref": "4" } ] } how can in easy way choose return player, , teams, rather return url team can data can obtained, like:
{ "id": 1, "name": "jon jones", "teams": "http://url/api/player/1/teams/" } edit: disabeling lazyloading suggested, get:
{ "id": 1, "name": "jon jones", "teams": [] } if thats way go, there "best practice" add uri teams in there?
you should disable lazy loading when building webservices - it's force explicit data being fetched. alternative drop [jsonignore] attributes on properties of classes don't want serializer at.
Comments
Post a Comment