c# - Implementing WebAPI with circular dependencies and loadable lists -
how possible implement such "smart" in webapi? have 2 classes want service. let's book store has relation book objects.
public class book { guid id { get; set; } string title { get; set; } store store { get; set; } } public class store { guid id { get; set; } string title { get; set; } string owner { get; set; } ienumerable<book> books { get; set; } }
i have backend sql server , entityframework adapter in code. how should make return list of books after need (call it), odata? can see have circular dependancies, makes json serializer show errors. resolve with:
config.formatters.jsonformatter.serializersettings.referenceloophandling = newtonsoft.json.referenceloophandling.serialize; config.formatters.jsonformatter.serializersettings.preservereferenceshandling = newtonsoft.json.preservereferenceshandling.objects;
but serialized data , response huge, not windows phone app. in cases need store object, in other cases need store referenced books.
in controllers user [queryable] attribute use odata queries. p.s. can't create more web-methods getbooks, getstore , on. should 1 method.
how resolve problem?
how resolve problem?
do not return entities api action methods.
instead, return models.
so instead of this:
public ienumerable<store> getstores() { using (var db = new mydbcontext()) { return db.stores; } }
do this:
public ienumerable<storemodel> getstores() { using (var db = new mydbcontext()) { var entities = db.stores; return entities.select(x => new storemodel { id = x.id, title = x.title, owner = x.owner, books = x.books.select(y => new bookmodel { id = y.id, title = y.title, storeid = x.id, }), }); } }
by doing way eliminate circular dependency graph. book
no longer references store
, storeid
.
Comments
Post a Comment