1. When using EF, there is a circular reference to JSON serialization of an object due to a database primary foreign key Association
// serialization of objects often has circular reference problems due to database primary foreign key association in EF // serializing a circular reference problem using the. Net-brought serialization tool list<student> list = _context.students.tolist (); New JavaScriptSerializer (); string str = ser. Serialize (list); Console.WriteLine (str);
Solution 1: Use the Newtonsoft.json tool to serialize, ignoring circular references
Mode of Use 1:
// Using the Newtonsoft serialization tool, you can set the Ignore circular reference Method 1 // But there is also the conversion of cyclic structure data, just the series of loops are fixed by the List <student> list = _context.students.where (q = Q.sno = = " 103 " ). ToList (); Jsonserializersettings settings = new Jsonserializersettings (); Settings. missingmemberhandling = Missingmemberhandling.ignore; // settings. referenceloophandling = Referenceloophandling.ignore; string result = Jsonconvert.serializeobject (list, settings); Console.WriteLine (result);
Mode of Use 2:
//using the Newtonsoft serialization tool, you can set the Ignore circular reference, Method 2//But there is also the transformation of the cyclic structure data, only the series of loops are fixedlist<student> list = _context.students.where (q = Q.sno = ="103"). ToList (); Jsonserializersettings Settings=Newjsonserializersettings (); Settings. Referenceloophandling=Referenceloophandling.ignore; Jsonserializer ser=jsonserializer.create (settings); using(StringWriter SW =NewStringWriter ()) {ser. Serialize (SW, list); Console.WriteLine (SW. ToString ()); }
Solution 2: Use the method annotations in Newtonsoft.json to ignore the associated properties when JSON is serialized
Focus on setting the Ignore method comment:
[Jsonignore] Public Virtual Get set; }
The default serialization will filter out the Ignore
// Using the Newtonsoft serialization tool, you can set the Ignore circular reference Method 3 (recommended) // This method combines method comments [Jsonignore], which is when JSON is serialized, The property specified by [Jsonignore] is ignored // This method is relatively common list<student> list = _context.students.where (q = Q.sno = = " 103 " ). ToList (); string result = Jsonconvert.serializeobject (list); Console.WriteLine (result);
// You can also display the specified ignore " 103 " ). ToList (); New jsonserializersettings (); = Missingmemberhandling.ignore; string result = jsonconvert.serializeobject (list, settings); Console.WriteLine (result);
Circular reference problem solving for Json serialization in EntityFramework--newtonsoft.json