c# - Serializing collections only one level deep with Entity Framework -
i'm running issue while attempting return recursive serialized objects generated entity framework 6 through web api. here's small example of problem:
[serializable] [datacontract] public partial class thing { public thing() { this.otherthings = new hashset<otherthings>(); } [datamember] public int thingid { get; set; } [datamember] public string thingname { get; set; } //not included in serialization public virtual icollection<otherthing> otherthings { get; set; } } [serializable] [datacontract] public partial class otherthing { public otherthing() { this.things = new hashset<things>(); } //i want these [datamember] public int otherthingid { get; set; } [datamember] public string otherthingname { get; set; } //do not want getallthings() avoid circular references public virtual icollection<things> things { get; set; } }
the decorators generated context.tt file, , there lot more properties in real object, making hand-editing each of these impossible - not mention files auto-generated.
i retrieve collection of things
database simple method:
public static class repo { internal static iqueryable<thing> getallthings() { //context initialized database context return context.things; } }
which returns entire collection of things
, contain otherthings
, each contain more things
. problem becomes obvious when try serialize web api response:
public class api { //this response serialized json public list<thing> getallthings() { var things = repo.getallthings(); //do here exclude return things.tolist(); } }
naturally, serializer fail (or overflow), because there circular references. add [dataignore]
offending properties , forget datacontracts altogether, if request collection of things
, want each connected otherthing
, , vice-versa.
can done?
assuming context.things of type dbset can use
return context.things.select(s => s).include(s => s.otherthings);
Comments
Post a Comment