I am using entity framework in a .NET Framework 4.6.1 API project.
I have a database with 3 tables like so :
When serializing my entities to JSON, everything is fine on the left side, but because I have a many-to-many relationship on the right side (The 3 could be replaced with n), and C can contain many different Bs, I end up, when trying to retrieve a single A Serializing the A's Bs and thus, the Bs' Cs, which in turn serializes pretty much my whole database when, really, I just want a single entity.
The problem is even worse when getting the whole collection of As, as it serializes my database multiple times, making it very slow and memory inefficient.
I have the following bit of code as reference handling :
config
.Formatters
.JsonFormatter
.SerializerSettings
.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
Can't find anything related or similar to that problem anywhere on the web.
CodePudding user response:
You can either use DTO or change JSON converter setting like below
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.All,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};