Quantcast
Channel: Geekswithblogs.net | asp.net Posts
Viewing all articles
Browse latest Browse all 56

Entity Framework POCO and JSON serialization

$
0
0
An application I've been working utilizes the jQuery DataTables plugin and server side processing for pagination.

My initial set up had my controller call a view model which in turn called my business layer to search for some entities. The view model method returned an object (DataTableModel) which encapsulates all of the properties needed for the DataTable plugin including a list of objects/entities. So far so good.

Next step has the controller serializing the DataTableModel to JSON so the DataTable plugin could do it's thing with it. Unfortunately this is where things fell down. Since the search results contained within the DataTableModel are a list of Entity Framework generated POCO objects with all of it's navigation properties the JSON serializer would try to serialized the entire object. Not surprising I suppose, however, I kind of expected it would figure out that if the navigation properties were null it would ignore them and not try to actually load them....but alas no.

Sooooo, my next adventure was figuring out how to attack this problem. The best practice it seems would be to have a view model for anything and everything you'd want to return to the UI whether directly to a view orvia Ajax. I don't necessarily have a problem with this, but at the same time I do not think it unrealistic to want to return POCO objects to the UI either.

Initially I decided to try and return a list of ExpandObjects for the JSON serializer to work with. This would serialize without error, however, the result is not quite what I'd hoped for. The result was the serializer creating key/value pairs for each property in the object vs. actually having an object property with respective value.

In the end I decided to have my Linq query return a dynamic with all of the information needed for display in my table. I then updated my DataTableModel to have a List<dynamic> vs. List<EntityFrameworkPOCO>. This allows the JSON serializer to work without fail.

Viewing all articles
Browse latest Browse all 56

Trending Articles