views:

58

answers:

1

Im working on a mvc 2.0 application using the entity framework. With the entityframework I use the repository pattern with poco objects. To start off with the issue, when I convert an entity object to json I get a circular reference error.

After some search I discovered that there are proxy's generated to support lazy loading. If there are navigation properties between two classes (A and B), this results in a circurar reference error. Quite understandable. So I try to work around it.

I disabled the proxies and the lazy loading. This works if I only want to load Class A. Instead of the proxy's there are now null values, so they can be parsed.

But now I want to load a class, for instance Orders and I want to see what customer placed the order:

Suppose I have class Customer that has a navigation property to Order (1 to more) and Order has a reversed navigation property to Customer. When I turn the proxys off, I get a nice json back with all the orders, but not with the Customers. When I turn the proxies on, I get a circular error.

But how could I get back the orders, with the customer that bought them. Is it possible to create a linq that retreives the orders and load the customers (I have a repository for both customers and orders)? Or is there a way to strip off the proxy-objects?

I hope my post is clear enoug and someone can help me

Regards

Patrick

A: 

Problem:
Right. So you have the relationship A -> B with B being the many side. in the EF model A gets a navigation property B and B gets a navigation property A. Circular reference... great...

Solution:
In your model, rightclick on the B's navigation property A and choose properties. Getter and setter there should both be public initially. Set the getter to Private.

Now something like this should work.

var results = from a in ctx.A.Include("B")
select a;

var list = results.ToList(); //This is important otherwise youll get a error that the context has been disposed on the next line.
return Json(list, JsonRequestBehavior.AllowGet);

Hope this helps.

PS: After reading my answer after posting it, I'm not so sure anymore that I'm really answering your question, sorry. Ill leave it up nonetheless.

n4rzul