Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore navigation properties when serializing

I'm using ASP.NET Web API with Entity Framework. I changed my default serializer to JSON.NET (cause the default DataContractSerializer didn't work at all with EF). Now it's better (it's working at least), however still not perfect. After sending the GET request I obtain all properties from one table plus lot's of data from navigation properties (so basically all data from other entities which have relation with entity I want to obtain...). How can I make it serializing only fields from this entity and not navigation properties?

Thanks for help

like image 393
Bart Avatar asked Oct 09 '22 10:10

Bart


2 Answers

Try to disable lazy loading.

The Json serializer is iterating through the properties of your entity to serialize them and therefore also is calling the getter of the navigation properties. Calling the getter of a navigation property = triggering lazy loading. Loading was delayed a bit but only until the serializer reached the navigation properties and caused an additional database query to fetch the child property values which then have been serialized as well.

like image 185
Slauma Avatar answered Oct 19 '22 20:10

Slauma


Disabling Lazy loading effectively remove the relationships stuff from the JSON serialization but the navigation properties will still appear in the JSON.

You may have to remove these navigation properties from your model if they are not usefull for you or select desired properties in your controller.

like image 2
Etienne Desgagné Avatar answered Oct 19 '22 20:10

Etienne Desgagné