The self referencing loop caused by the EF entity to JSON

Source: Internet
Author: User

Problem Description: When doing the project in the previous period, the entity to be taken to the Redis cache to store The Times multiple reference errors.

The self referencing loop detected the ' checkitemcategory ' with type.

I. Details of the question

1. Introduction of Chectitemcategory and Checkitem entities

2, we use EF to take the list<checkitemcategory>, in the form of JSON stored in Redis. But in the Jsonconvert.serializeobject times multiple reference errors.

3, after the reason, Newtonsoft.json to the Entity (Checkitemcategory) serialization, will traverse all the properties in the Checkitemcategory to convert. When the navigation property Checkitems is encountered, the Checkitems data (EF lazy load) continues to be requested to the database. When converting checkitem entities, there are checkitemcategory navigation properties inside the Checkitem entity. Checkitemcategory and Checkitem Reference each other, multiple references to the dead loop problem.

Second, the solution

1, Method 1. Recommended for this.

This property is ignored by adding the [Jsonignore] attribute on the Checkitems navigation property of the entity.

For Newtonsoft.json advanced usage See http://www.cnblogs.com/yanweidie/p/4605212.html

2, Method 2. Delete the Checkitems property in the Checkitemcategory class. However, this method is not a cure, (1) The EF configuration of the foreign key relationship needs to use

(2) In specific applications may have been using their relationship to delay loading, business operations.

(3) When taking Checkitem to JSON, the checkitemcategory will also be removed and transferred to the JSON to compare pits.

Iii. extension of thinking

When returning results with WEBAPI, do not return to entity directly, because the navigation properties are also removed. Other data information was exposed.

The self referencing loop caused by the EF entity to JSON

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.