Entity Framework Circular References

One of the first issues I encountered returning serialized, nested (“deep”) entities using EF5 with the (MVC4) ASP.NET Web Api was the “Self Referencing loop” exception*

For any property you don’t want exposed, make the Getter: Internal & Setter: Public.

image

Doing this on the navigation properties that reference the parent that reference it will prevent the “circular reference” error:

image

Doing this on standard (field) properties will prevent those fields from being serialized & exposed (for example, in the ASP.NET Web Api).

image

  1. This means there is no need to add Newtonsoft.Json.PreserveReferencesHandling settings to your Global.asax Application_Start which results in REALLY ANNOYING $ref & $id properties being added to your serialized results).

  2. This also means there is no need to create partial classes with MetadataType attributes for every class that define [JsonIgnore] or [XmlIgnore] attributes on specific properties to prevent this

    Note: This is still a GREAT way to add things like data validation attributes to properties generated using db-first EF. They’re just not necessary to prevent the circular ref exception.

I hope this helps save someone some of the time I spent this week attempting to work around it.

Big thanks to @DavidBitton for the ongoing Twitter dialog that led to this easier-to-implement-than-other-findings solution.


*{“Message”:”An error has occurred.”,”ExceptionMessage”:”The ‘ObjectContent`1’ type failed to serialize the response body for content type ‘application/json; charset=utf-8’.”,”ExceptionType”:”System.InvalidOperationException”,”StackTrace”:null,”InnerException”:{“Message”:”An error has occurred.”,”ExceptionMessage”:”Self referencing loop detected for property ‘Customer’ with type ‘Namespace.Customer. Path ‘CustomerOrders[0]’.”,”ExceptionType”:”Newtonsoft.Json.JsonSerializationException”,”StackTrace”:”   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CheckForCircularReference(JsonWriter writer, Object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value)\r\n   at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value)\r\n   at System.Net.Http.Formatting.JsonMediaTypeFormatter.<>c__DisplayClassd.<WriteToStreamAsync>b__c()\r\n   at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)”}}

8 Comments on “Entity Framework Circular References”

  1. James Blake Says:

    Wonderful, thank you!

    Reply

  2. Kevin Templer Says:

    I know this is an old post and maybe the author won’t see this, but….this just bit me… you saved me ooodles of time.

    Thanks a bunch

    Reply

  3. Rui Menezes Says:

    Thanks, The only solution that worked for Database First.

    Reply

  4. sundar Says:

    Thanks thanks:) saved :)

    Reply

  5. Abu Says:

    Awesome. Thanx so much. Struggling with this for two days. That being said, Rui is right this is the only solution that worked for database first.

    Reply

  6. Murat Says:

    just spent 2 days now and have had this problem before too, could never think of this solution. Thank!

    Reply

  7. Margaret Says:

    So thankful to the author! Having been struggled for this for days. Use F12 to find the exact error, and bing it, that brought to me to this site! Yay!

    Reply

  8. Chris Says:

    Took a lot of searching to find this article, but it helped me. Thanks!

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: