AbuYazan AbuYazan - 1 month ago 16
JSON Question

A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'

The below code will read oracle table and return json result, to the view.
The data are loaded successfully into the datalist, however the view is throwing the below error:


A circular reference was detected while serializing
an object of type 'System.Reflection.RuntimeModule'.


Q1: What I can do to fix the error? I already have a model defined for the data I need to retrieve (see the below model definition)

Q2: Is the above method is the best practice to read a database and return json?

public JsonResult StudList()
{
string SQL = "select id, name, div_code, block, from students where ....."; //see the below model
var con = DB.GetConnection();
con.Open();
OracleDataAdapter oraAdapt = new OracleDataAdapter(SQL, con);
DataTable dt = new DataTable();
oraAdapt.Fill(dt);
con.Close();
con.Dispose();
List<DataRow> dtList = dt.AsEnumerable().ToList();
return Json(dtList, JsonRequestBehavior.AllowGet);
}


Model:

public class GetSDetailsModel
{
public List<GetStudentSearchModel> GetStudentSearchModel { get; set; }
}


public class GetStudentSearchModel
{
public string id { get; set; }
public string name { get; set; }
public string div_code { get; set; }
public string level_code { get; set; }
public string program_code { get; set; }
public string major_code { get; set; }
public string PGPA { get; set; }

}

Answer

As David said in comment you need to convert DataRow's to List<GetStudentSearchModel>. You can do that using Linq's Select method, passing lambda expression that creates GetStudentSearchModel from DataRow object. The code would be like this:

public JsonResult StudList()
{
    string SQL = "select id, name, div_code, block, from students where ....."; //see the below model 
    var con = DB.GetConnection();
    con.Open();
    OracleDataAdapter oraAdapt = new OracleDataAdapter(SQL, con);
    DataTable dt = new DataTable();
    oraAdapt.Fill(dt);
    con.Close();
    con.Dispose();
    List<GetStudentSearchModel> dtList = dt.AsEnumerable()
        .Select(row => new GetStudentSearchModel
        {
            id = row["id"],
            name = row["name"],
            div_code = row["div_code"],
            //...
        }).ToList(); 
    return Json(dtList, JsonRequestBehavior.AllowGet); 
}

Just add rest of your fields to initializer block.

Comments