Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove circular reference in Entity Framework?

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

like image 510
Roy Avatar asked Jan 21 '10 07:01

Roy


People also ask

How to remove circular reference in C#?

To handle the problem of circular references in C#, you should use garbage collection. It detects and collects circular references. The garbage collector begins with local and static and it marks each object that can be reached through their children. Through this, you can handle the issues with circular references.

How do I use lazy loading in Entity Framework?

Lazy loading means delaying the loading of related data, until you specifically request for it. When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook.


4 Answers

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);
like image 140
Craig Stuntz Avatar answered Sep 24 '22 10:09

Craig Stuntz


I have solved this problem in EF 3.5 By changing the Child's navigation property Getter from public to Internal.

like image 41
Asmussen Avatar answered Sep 21 '22 10:09

Asmussen


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.

like image 36
Charlie Avatar answered Sep 24 '22 10:09

Charlie


On serverlevel:

[DataContract(IsReference = true)] 

MSDN

like image 26
D.Kempkes Avatar answered Sep 20 '22 10:09

D.Kempkes