views:

181

answers:

1

I noticed people wrote about this circular reference problem quite a bit before but no solution was ever posted.

I'm talking about this error: "A circular reference was detected while serializing an object of type 'DocInvoice.Models.Clients'."

Has anyone tried serializing it to JSON with Json.NET library?

If I have Linq to entities queries, is my only option to hand code entity properties and leave out those that are Navigational properties? Because those are the ones making problems..

It is annoying though because you have to hand write like dozens (or more) entity properties in Linq "new" statement. For instance, if I want all the properties I can do this but it results in circular reference error:

        var clients =
                    from client in edmx.Clients
                    from postcode in edmx.PostCodes
                    where (client.client_firstname.StartsWith(q) || client.client_lastname.StartsWith(q))
                          && postcode.postcode == client.PostCodes.postcode
                    select new {client, postcode};

the only other option is:

...

select new {client.client_id, client.client_firstname, ....., ... , postcode.postcode}; ...
+2  A: 

Projecting onto an anonymous type (your second example) is the right way to do it. That's the only thing which prevents your code from leaking info if additional properties are added to the entity later on. The anonymous type clearly limits what your code returns.

Craig Stuntz
Nice comment and explanation, thanks
mare