Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing LINQ-objects to JSON-strings - HUGE strings

I am using LINQ to access my database, and thereby gets a LINQ-created object which I want to send to the browser (this is a webservice) as a JSON-object. This works well by now, but when I add some testdata to the database (about 10-20 entries in each table) this fails miserably. The reason is that the LINQ-object contains all the referenced objects. This becomes huge pretty fast. Eg. each resourcetype contains all its resources which contains all reservationlines which contains each reservations..

Do you have any tips on how I should resolve this? Is there a setting in the serializer I can set? I use json.net for serializing the objects. Or is there some setting in LINQ?

In the best case I don't want to create new objects before I serialize them, since it is very convenient to just serialize the LINQ-objects directly :)

like image 487
Espen Herseth Halvorsen Avatar asked Jan 23 '26 21:01

Espen Herseth Halvorsen


1 Answers

The best practice, at least for the moment, is to not serialize LINQ to SQL objects, or Entity Framework entities. The main reason for that is that they include implementation-dependent data from the base classes.

Instead, serialize what you want serialized. Use Data Transfer Objects matching exactly what you want to send, and copy from the LINQ to SQL objects into them before sending.

like image 101
John Saunders Avatar answered Jan 26 '26 21:01

John Saunders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!