views:

138

answers:

2

Hi,

The circular reference between my Customer and Order entities caused a exception during serialization. Is there anyway to force EF to generate one-direction reference between these two entities? Thanks in advance!

+2  A: 

When you create an association in model designer (right click add->association) you'll get a popup windows which looks like this:

Add association window

Notice the navigation property check boxes, you can deselect them if you don't want them to be generated. To solve your circular reference problem, make sure only one or none are checked, not both.

Charlie
Sorry, I can't catch up what you said. Can you put it more specify? Thanks!
Roy
Updated with screenshot
Charlie
Thanks Charlie, but I cann't see the picture. And my designer don't have checkbox on it. :( I'm using Visual Studio 2008.
Roy
Ok, I'm using Entity Framework 4.0 on VS2010 beta 2...maybe this isn't something you can do in the older version of EF.
Charlie
In 3.5 SP1 you can't remove navigation properties using the designer, you have to resort to removing them from the ConceptualModel section of the XML inside the EDMX file. However I think Craig's answer is much better. You don't necessarily want to change you model to solve a serialization problem. There is only so much you can do by changing the model.
Alex James
@Charlie, James: Thanks a lot. I'm going to add Dto to my project.
Roy
@Alex James. Yep I'll go with that as well, Craigs solution is preferable
Charlie
+3  A: 

When I need to serialize, I generally project onto other types. This eliminates circular references, plus other data I don't want serialize. For example:

var q = (from c in Repository.Customers()
         where c.Id == id
         select new 
         {
             Name = c.Name,
             Orders = from o in C.Orders
                      select new
                      {
                          Date = o.Date
                      }
         }).First();
return Json(q);
Craig Stuntz