The ASP. NET Mvc-web API encountered loop Reference when using the Entity Framework

Source: Internet
Author: User

Original address: http://www.it165.net/pro/html/201210/3932.html

Recently started to study web API, good luck the first test project encountered a problem @@-when new control is selected [API Controller woth read/write actions, using Entity Framework] Then use the Northwnd database, data table select Orders,order_details,products.



The front-end JavaScript program code is as follows

View Source print? 01. @section scripts{ 02. <script type= "text/javascript" > 03. $(document).ready( function () { 04.  05. $.getJSON( ‘/api/order/‘ , function (data) { 06. alert(data); 07. }) 08. .error( function (jqXHR, textStatus, err) { 09. alert( ‘Error: ‘ + err); 10. }); 11. }); 12. </script> 13. }

Error occurred after execution, query full error description for self referencing loop detected ..., that is, circular reference.


This error message is familiar and suddenly reminds me of a similar situation in the previous development of Silverlight RIA service. After searching the internet for reasons, the problem is the same, because the ASP. NET MVC Web API preset uses json.net as the output transform. In the case of a preset, Json.NET will automatically parse the properties of the object to be output, and say that the output object in this example is Order, which has a property of Order_Details, and Order_Details has a property reference to order, Therefore, a cyclic dependency problem is generated, resulting in an error.

There are three ways to deal with this problem www.it165.net

1. The simplest way is to start with the Entity Framework and deactivate lazyloading and proxycreation. Because Lazyloading is deactivated, its properties Order_ when the order object is parsed json.net Details returns Null (does not load automatically). So this problem is avoided.

Of course, the disadvantage of this approach will cause subsequent programs to access the entity object at the expense of lazyloading convenience, and need to handle this problem manually.

View Source print? 1. db.Configuration.LazyLoadingEnabled = false ; 2. db.Configuration.ProxyCreationEnabled = false ; 3.  4. return db.Orders.AsEnumerable();

2. Set Json.NET Ignore loop reference

Set config through App_start's WebApiConfig.cs. Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore ;

When using this method, it is important to note that it simply ignores the error of the circular reference, but in fact it automatically parses the properties of the object to be output, so that if the data is dependent, it may produce an infinite loop.

3. Set Json.NET to avoid circular reference

Through App_start's WebApiConfig.cs, set

Config. Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;

Config. Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;

The difference between this approach and 2 is that it replaces the repeated objects with a representative, such as the JSON format below
1: [{"$id": "1", "category": {"$id": "2", "products": [{"$id": "3", "category": {"$ref": "2"}, "id": 2, "Name": "Yogurt"},{"$ Ref ":" 1 "}]," id ": 1," name ":" Diary "}," id ": 1," Name ":" Whole Milk "},{" $ref ":" 3 "}]

So for data this approach will automatically parse the properties of the object to be exported, just to avoid outputting too much data.

4. Manual setting avoids circular reference

As in the 3 mode, you can set each property to be output more precisely through [Jsonignore] and [Jsonobject (IsReference = True)] details.

The disadvantage is 1. Set the Miscellaneous. 2. Only universal settings can not be excepted. 3. The setting cannot be separated from the entity Object class because it must be set directly or through the partial class mode

The above approach actually has its pros and cons, and there is no generic model that needs to be looked at, as is the problem with the earlier RIA service, but a more generic pattern here is to use the method 1+ method 2 or 3.

Deactivate lazyloading, and use the program's way (through the Include method) to determine which properties to output.

The ASP. NET Mvc-web API encountered loop Reference when using the Entity Framework

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.